Golang结构体中的类型指针

huangapple go评论78阅读模式
英文:

Golang pointer of type within a struct

问题

// 你可以编辑这段代码!
// 点击这里开始输入。
package main

import "fmt"

type Testing struct {
	firstname string
}

type Another struct {
	*Testing
}

func main() {
	var f = Another{Testing: &Testing{firstname: "sasdf"}}
	fmt.Println(f)
}

在这段代码中,我使用了一个指针在结构体中。这是我在仓库中见过的一种用法,但我不太理解。

这是做什么用的?起初我以为它会扩展Testing结构体的属性,但事实并非如此。

根据我的观察,Another结构体可能有一个名为Testing的属性,它保存一个值。如果给它赋值var f = Another{Testing: &Testing{firstname: "afsdf"}},然后打印输出,会得到一个包含内存地址的结构体。所以这个语法是创建一个新的结构体,其中包含一个指向类型为T的对象的指针,该对象的名称与类型的名称相同。

英文:
// You can edit this code!
// Click here and start typing.
package main

import "fmt"

type Testing struct {
	firstname string
}

type Another struct {
	*Testing
}

func main() {
	var f = Another{firstname: "sasdf"}
	fmt.Println(f)
}

Here I've used a pointer in the struct. Its something i've seen used in repository. But i'm not understanding.

What does this do? First i expected it would extend the properties of Testing struct. This ins't true.

From my inspected the Another struct may have a Testing property that holds a value. Giving it var f = Another{Testing: &Testing{firstname: "afsdf"}} and printing yields a struct containing a memory address. Do this syntax is a new struct with a property that contains a pointer to a object of T named the name of the type

答案1

得分: 2

根据规范中的说明:

> 声明了类型但没有显式字段名的字段被称为嵌入字段。

> 在结构体 x 的嵌入字段中,字段或方法 f 被称为被提升的,如果 x.f 是一个合法的选择器,表示该字段或方法 f
> 被提升的字段表现得像结构体的普通字段,但不能在结构体的复合字面量中用作字段名。

最后引用的那句话解释了为什么复合字面量 Another{firstname: "sasdf"} 无法工作。

英文:

From the spec:

>A field declared with a type but no explicit field name is called an embedded field.

>A field or method f of an embedded 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.

The last quoted sentence is why the composite literal Another{firstname: "sasdf"} did not work.

huangapple
  • 本文由 发表于 2022年2月18日 03:53:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/71164578.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定