./main.go:23:15:无效的类型断言:bar.(傅)(左侧为非接口类型栏)



我很难理解为什么这段代码无法构建。

package main
import (
"fmt"
)
type Foo interface {
Cose() string
}
type Bar struct {
cose string
}
func (b *Bar) Cose() string {
return b.cose
}
func main() {
bar := Bar{
cose: "ciaone",
}
ii, ok := bar.(Foo)
if !ok {
panic("Maronn")
}
fmt.Println(" cose : " + ii.Cose())
}

接口是一个相反的操作 - 将接口转换为特定类型。喜欢:

package main
import (
"fmt"
)
type Foo interface {
Cose() string
}
type Bar struct {
cose string
}
func (b *Bar) Cose() string {
return b.cose
}
func main() {
bar := Foo(&Bar{
cose: "ciaone",
})
ii, ok := bar.(*Bar)
if !ok {
panic("Maronn")
}
fmt.Println(" cose : " + ii.Cose())
}

演示:https://play.golang.org/p/ba7fnG9Rjn

类型断言适用于您的情况,通过闭包工作:

package main
import (
"fmt"
)
type Foo interface {
Cose() string
}
type Bar struct {
cose string
}
func (b *Bar) Cose() string {
return b.cose
}
func main() {
bar := &Bar{
cose: "ciaone",
}
ii := func(bar interface{}) Foo {
ii, ok := bar.(Foo)
if !ok {
panic("Maronn")
}
return ii
} (bar)
fmt.Println(" cose : " + ii.Cose()  )
}

最新更新