空接口是接口类型的特殊形式,空接口没有任何方法,因此任何类型都无须实现空接口。从实现的角度看,任何值都满足这个接口的需求。因此空接口类型可以保存任何值,也可以从空接口中取出原值。
interface{} 与 []interface{}
interface{}转struct
package main
import (
"encoding/json"
"fmt"
)
type user struct {
Id int `json:"id"`
Name string `json:"name"`
}
func main() {
newUser:=user{
Id: 1,
Name: "杉杉",
}
var newInterface1 interface{}
//第一种使用interface
newInterface1=newUser
fmt.Printf("使用interface: %v",newInterface1.(user))
//第二种使用json
var newInterface2 interface{}
newInterface2=newUser
resByre, resByteErr := json.Marshal(newInterface2)
if resByteErr != nil {
fmt.Printf("%v",resByteErr)
return
}
var newData user
jsonRes := json.Unmarshal(resByre, &newData)
if jsonRes != nil {
fmt.Printf("%v",jsonRes)
return
}
fmt.Printf("使用 json: %v",newData)
}