簡體   English   中英

Golang:將struct轉換為嵌入在offset 0 struct

[英]Golang: convert struct to embedded at offset 0 struct

我有一些不同的結構,如Big with Small嵌入在偏移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 )?

盡可能避免使用unsafe的。 上面的任務可以使用反射( reflect包)來完成:

var v interface{} = Big{Small{1}, 2}

rf := reflect.ValueOf(v)
s := rf.FieldByName("Small").Interface()

fmt.Printf("%#v\n", s)
fmt.Printf("%#v\n", s.(Small).val)

輸出(在Go Playground上試試):

main.Small{val:1}
1

筆記:

這適用於任何領域,而不僅僅是第一個領域(“偏移0”)。 這也適用於命名字段,不僅適用於嵌入字段。 但這對於未導出的字段不起作用。

type Small struct {
    val int
}

type Big struct {
    Small
    bigval int
}

func main() {
    var v = Big{Small{10},200}
    print(v.val)
}

雖然回答是有效的,但它有性能損失,並不是Go的慣用語。

我相信你應該使用界面。 像這樣

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM