خطأ "cannot convert data (type interface{}) to type string: need type assertion" في Go
مرحباً بالجميع! لقد بدأت للتو في تعلم 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` من النوع `interface{}`، لكن كيف يمكنني الحصول على قيمة السلسلة؟ جربت كتابة `data.(map[string]interface{})["name"]` لكنها لا تزال لا تعمل. أرجو التوضيح، ما الخطأ الذي أرتكبه وكيف يمكنني استخراج القيم من الـ interfaces في Go بشكل صحيح. شكراً مسبقاً!
<<>>