Go结构中的无名字段? [英] Nameless fields in Go structs?

查看:115
本文介绍了Go结构中的无名字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  package main 

importfmt

type myType struct {
string
}

func main(){
obj:= myType {Hello World}

fmt.Println(obj)
}

结构中无名字段的用途是什么?



您可以像使用命名字段一样访问这些字段吗?

嵌入Go :您嵌入结构中的匿名字段:这通常与嵌入式结构一起使用,而不是像 string 这样的基本类型。这种类型没有推广领域来公开。


结构<$ c中匿名字段的字段或方法 f 如果 xf 是一个合法选择器,表示该字段或方法<$ c $>,则称$ c> x 提升 c> f



升级字段的作用类似于结构的普通字段,只是它们不能用作结构的复合字面值中的字段名。


(这里 string 本身没有字段)



请参阅嵌入何时使用指针的嵌入类型示例。


是否可以像使用命名字段一样访问这些字段?


A fmt.Println(obj.string)会返回 Hello World ,而不是 {Hello World}


package main

import "fmt"

type myType struct {
    string
}

func main() {
    obj := myType{"Hello World"}

    fmt.Println(obj)
}

What is the purpose of nameless fields in structs?

Is it possible to access these fields like you can do with named fields?

解决方案

See "Embedding in Go ": you embed an anonymous field in a struct: this is generally used with an embedded struct, not a basic type like string. That type has no "promoted field" to expose.

A field or method f of an anonymous field in a struct x is called promoted if x.f is a legal selector that denotes that field or method f.

Promoted fields act like ordinary fields of a struct except that they cannot be used as field names in composite literals of the struct.

(here string has no field in itself)

See an example of type embedding in "Embeddding when to use pointer".

Is it possible to access these fields like you can do with named fields?

A fmt.Println(obj.string) would return Hello World instead of {Hello World}.

这篇关于Go结构中的无名字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆