doqdcks3948 2019-02-12 15:15
浏览 117
已采纳

如何使用反射获取字符串指针的变量名?

I want to get the name of a field name by using reflection. I pass the string as a pointer and then I want to retrieve the variable name in the function.

type FooBar struct {
    foo *string
}

func bar(s *string) {

    var name string

    // TODO: Get name of the field that s is pointing to!

    fmt.Println("Expected string is foo: " + name)
}

func main() {
    f := Foo{"bar"}
    bar(f.s)
}

I tried getting the value of s with

val := reflect.ValueOf(s)

and then I am out of my depth to get the variable name.

I should mention that there are multiple fields in my struct and I don't know in advance which field is in question.

Any help is appreciated. Thanks

  • 写回答

1条回答 默认 最新

  • douduan5073 2019-02-12 15:22
    关注

    You cannot do this.

    When you write f.s all you have is a pointer to string. The information that some fields in some struct happens to have this as a value is completely lost/unavailable.

    I'm not going to recommend package unsafe here: You must redesign.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥60 pb数据库修改或者求完整pb库存系统,需为pb自带数据库
  • ¥15 spss统计中二分类变量和有序变量的相关性分析可以用kendall相关分析吗?
  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错
  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)
  • ¥15 相敏解调 matlab
  • ¥15 求lingo代码和思路