Go में "cannot convert data (type interface{}) to type string: need type assertion" त्रुटि
सभी को नमस्ते! मैंने अभी-अभी Go सीखना शुरू किया है और एक अजीब त्रुटि का सामना किया। मैं एक सरल प्रोग्राम लिख रहा हूँ जो JSON से डेटा प्राप्त करता है और उसका उपयोग करने का प्रयास करता है।
यहाँ मेरा कोड है:
```go
package main
import (
"encoding/json"
"fmt"
)
func main() {
jsonString := `{"name": "John", "age": 30}`
var data interface{}
json.Unmarshal([]byte(jsonString), &data)
name := data["name"] // त्रुटि: cannot convert data (type interface {}) to type string: need type assertion
fmt.Println(name)
}
```
मुझे उम्मीद थी कि `data["name"]` स्ट्रिंग "John" लौटाएगा, लेकिन कंपाइलर त्रुटि देता है: "cannot convert data (type interface {}) to type string: need type assertion"। मैं समझता हूँ कि `data` का type `interface{}` है, लेकिन मैं स्ट्रिंग मान कैसे प्राप्त करूँ? मैंने `data.(map[string]interface{})["name"]` लिखने की कोशिश की, लेकिन फिर भी काम नहीं करता। कृपया समझाएँ कि मैं क्या गलत कर रहा हूँ और Go में interfaces से मान कैसे सही ढंग से निकालें। पहले से धन्यवाद!
<<>>