将 interface{} 转换为类型

说我有这样的事情:


type Foo struct{

   Bar string

}


func Exported (v interface{}){

 // cast v to Foo

}

有没有办法在导出函数中将 v 转换为 Foo?


我尝试了这样的类型断言:


func Exported (v interface{}){


  v, ok := v.(Foo)


  if !ok {

    log.Fatal("oh fuk")

  }


  // but v.Bar is not available here tho ??


}

问题是如果我在断言之后尝试访问 v.Bar,它不会编译。


12345678_0001
浏览 133回答 3
3回答

Qyouu

问题出在变量名上v。请参考以下代码func Exported (v interface{}){  v, ok := v.(Foo)  if !ok {    log.Fatal("oh fuk")  }  // but v.Bar is not available here tho ??}在这里,接口名称是v并且在类型转换之后,它被分配给变量v 因为v是interface类型,你无法检索Foo结构的值。要克服这个问题,请在类型转换中使用另一个名称,例如b, ok := v.(Foo)你将能够Bar使用获得价值b.Bar工作示例如下:package mainimport (    "log"    "fmt")func main() {    foo := Foo{Bar: "Test@123"}    Exported(foo)}type Foo struct{    Bar string}func Exported (v interface{}){    // cast v to Foo    b, ok := v.(Foo)    if !ok {        log.Fatal("oh fuk")    }    fmt.Println(b.Bar)}

慕慕森

func main() {    f := Foo{"test"}    Exported(f)}type Foo struct{    Bar string}func Exported (v interface{}){    t, ok := v.(Foo)    if !ok {        log.Fatal("boom")    }    fmt.Println(t.Bar)}

九州编程

我犯了这个错误:func Exported (v interface{}){  v, ok := v.(Foo)  if !ok {    log.Fatal("oh fuk")  }  // but v.Bar is not available here tho ??}您需要使用不同的变量名称:func Exported (x interface{}){  v, ok := x.(Foo)  if !ok {    log.Fatal("oh fuk")  }  // now v.Bar compiles without any further work}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go