登录
首页 >  Golang >  Go问答

将接口{}转换为指定类型

来源:stackoverflow

时间:2024-03-15 14:48:30 285浏览 收藏

Golang不知道大家是否熟悉?今天我将给大家介绍《将接口{}转换为指定类型》,这篇文章主要会讲到等等知识点,如果你在看完本篇文章后,有更好的建议或者发现哪里有问题,希望大家都能积极评论指出,谢谢!希望我们能一起加油进步!

问题内容

假设我有这样的东西:

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,它不会编译。


解决方案


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)
}

问题出在变量名 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 由于 vinterface 类型,因此您无法检索 foo 结构体的值。

要解决这个问题,请在类型转换中使用另一个名称,例如

b, ok := v.(foo)

您将能够使用 b.bar 获取 bar

工作示例如下:

package main

import (
    "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)
}

今天关于《将接口{}转换为指定类型》的内容介绍就到此结束,如果有什么疑问或者建议,可以在golang学习网公众号下多多回复交流;文中若有不正之处,也希望回复留言以告知!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>