duanqianwei2485 2013-01-07 06:35
浏览 25
已采纳

获取结构元素的静态类型

I've looked in the Golang documentation and haven't seen an example of how to achieve what I'm looking to do. Specifically, I'm trying to write a map from inodes, represented by syscall.Stat_t.Ino, which has type uint64 on my machine, to ino_entry, defined as

type ino_entry struct {
    st    *syscall.Stat_t
    nodes []string
}

where nodes represents the names of all the files hard linked to the inode.

However, I want to avoid putting the literal type uint64 in the specification of the map if I can. That is, instead of writing map [uint64] ino_entry, I'd prefer to write map [typeof(syscall.Stat_t.Ino)] ino_entry, where typeof(x) returns the static (i.e., compile-time) type of x. I've tried map [syscall.Stat_t.Ino] ino_entry and, by analogy with type switches, map [syscall.Stat_t.Ino.(type)] ino_entry, but both of these are syntax errors. Needless to say, map [reflect.Typeof(syscall.Stat_t.Ino)] ino_entry doesn't work. As far as I can tell, the only way to implement this without hardcoding the type of the structure element is to use inomap := make(map [interface{}] ino_entry) and then access the elements using type assertions (I don't know the correct syntax for this though).

Is there a way to declare the type of a variable based on the static type of another variable, or struct or interface member, without hardcoding that type explicitly?

  • 写回答

3条回答 默认 最新

  • dongzhi2014 2013-01-07 19:51
    关注

    It looks like you are trying to use Reflection to ensure machine portability. If that is the case there is a better tool you can use.

    go build can handle conditional file inclusion for a build based on arch and os.

    So create some files for each arch and os combination you support. At the top of each file add some build constraints.

    // +build linux,386 for instance will cause the go command to only use this file on linux machines with a 386 arch.

    Then in that file add a type alias for the type that fits that arch: type Ino uint64

    Finally create your map as a map[Ino]ino_entry.

    Wala! machine portability using type aliasing and conditional file inclusion for go.

    You can read more about go's build constraints here: http://golang.org/pkg/go/build/

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置