我需要一種方法來動態地將結構/接口轉換回其原始對象。 我可以在裏面添加方法/函數。基本上我需要的是這樣的:如何將接口{}返回到其原始結構中?
MyStruct => Interface{} => MyStruct
當最終轉化我不知道除了什麼來的結構內的原結構任何東西,所以我不能只是這樣:
a.(MyStruct)
我需要一種方法來動態地將結構/接口轉換回其原始對象。 我可以在裏面添加方法/函數。基本上我需要的是這樣的:如何將接口{}返回到其原始結構中?
MyStruct => Interface{} => MyStruct
當最終轉化我不知道除了什麼來的結構內的原結構任何東西,所以我不能只是這樣:
a.(MyStruct)
否:如this thread
中提到Go既不是協變也不是逆變。類型是equal或者它們不是。
您必須將結構拆開並處理件,或者use reflection。
類型斷言只是「assertions」,而不是「任何形式的」強制「。
參見this thread,這提醒我們:
- 指針是一種類型。
- 結構是另一種類型。
- 整數是另一種類型。
- 浮點數是另一種類型。
- 布爾型是另一種類型。
接口的原理涉及連接到一個類型
T
,不是什麼類型T
是方法。接口類型由一組方法定義。
實現這些方法的任何值都可以分配給該類型的接口值。
這會使從接口到具體類型的轉換非常困難。
你至少需要知道它可能的類型。有幾個案例,1,你認爲你可能知道它是什麼。 2.你有一個可能的類型列表,3.你的代碼對底層類型一無所知。
s2, ok := thinger.(*MyStruct)
https://play.golang.org/p/rL12Lrpqsyu 注:
...
package main
import (
"fmt"
)
type MyStruct struct {
Thing string
}
func (s *MyStruct) Display() {
fmt.Println(s.Thing)
}
type Thingable interface {
Display()
}
func main() {
s := &MyStruct{
Thing: "Hello",
}
// print as MyThing
s.Display()
var thinger Thingable
thinger = s
// print as thingable interface
thinger.Display()
// convert thinger back to MyStruct
s2 := thinger.(*MyStruct) // this is "type assertion", you're asserting that thinger is a pointer to MyStruct. This will panic if thinger is not a *MyStruct
s2.Display()
}
您可以在這裏看到這些內容起作用。如果成功,則ok將爲true,否則爲false。
...
package main
import (
"fmt"
"reflect"
)
type MyStruct struct {
Thing string
}
type MyStruct2 struct {
Different string
}
func (s *MyStruct) Display() {
fmt.Println(s.Thing)
}
func (s *MyStruct2) Display() {
fmt.Println(s.Different)
}
type Thingable interface {
Display()
}
func main() {
s := &MyStruct{
Thing: "Hello",
}
// print as MyThing
s.Display()
var thinger Thingable
thinger = s
// print as thingable interface
thinger.Display()
// try to identify thinger
switch t := thinger.(type) {
case *MyStruct:
fmt.Println("thinger is a *MyStruct. Thing =", t.Thing)
case *MyStruct2:
fmt.Println("thinger is a *MyStruct2. Different =", t.Different)
default:
fmt.Println("thinger is an unknown type:", reflect.TypeOf(thinger))
}
}
你可以試試在這裏https://play.golang.org/p/7NEbwB5j6Is
Go是靜態類型的,所以如果你需要一個特定類型的結構體,你必須知道在編譯時是什麼類型 – JimB
'除了結構體內部什麼都不瞭解原始結構體什麼?這是否意味着? – Ankur