戈朗 : convert struct to embedded at offset 0 struct

标签 go struct interface embedding

我有一些不同的结构,例如 BigSmall 嵌入在偏移量 0 处。 我如何从代码访问 Small 的结构字段,它对 Big 类型一无所知,但已知 Small 是在偏移量 0 处?

type Small struct {
    val int
}

type Big struct {
    Small
    bigval int
}

var v interface{} = Big{}
// here i only know about 'Small' struct and i know that it is at the begining of variable
v.(Small).val // compile error

似乎编译器在理论上能够操作这样的表达式,因为它知道 Big 类型在偏移量 0 处嵌入了 Small 类型。有什么办法可以做到这一点事情(可能与 unsafe.Pointer)?

最佳答案

虽然带反射的答案有效,但它会降低性能并且不是 Go 的惯用语言。

我相信你应该使用接口(interface)。像这样

https://play.golang.org/p/OG1MPHjDlQ

package main

import (
    "fmt"
)

type MySmall interface {
    SmallVal() int
}

type Small struct {
    val int
}

func (v Small) SmallVal() int {
    return v.val
}

type Big struct {
    Small
    bigval int
}

func main() {
    var v interface{} = Big{Small{val: 3}, 4}
    fmt.Printf("Small val: %v", v.(MySmall).SmallVal())
}

输出:

Small val: 3

关于戈朗 : convert struct to embedded at offset 0 struct,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39143091/

相关文章:

arrays - 在MATLAB中: How should nested fields of a struct be converted to a cell array?

c++ - 为什么不允许在非推导上下文中使用基类定义,以及如何解决这个问题?

c - C 中的接口(interface)

google-app-engine - 如何在 GAE Go 中对 slice 进行排序

java - 处理实现通用接口(interface)的枚举(迭代、反序列化)

java - 从终端编译 java 源代码的最简单方法?

Go mod private repo 在 cloudbuild 中读取错误的路径

mongodb - 定义ID int64时如何自动生成ID int64 `bson:“_id”`

go - 如何从golang的 map 中统一获取 key 片?

c# - .NET : Unable to cast object to interface it implements