gpt4 book ai didi

go - 类型定义 : Pointer vs Value

转载 作者:行者123 更新时间:2023-12-01 22:43:47 27 4
gpt4 key购买 nike

我是 Go 新手,想 延长 treemap.Map来自 GoDS项目。

我首先为 treemap.Map 定义了一个类型别名。 :

import "github.com/emirpasic/gods/maps/treemap"

type Index = treemap.Map

func (idx Index) Add(k int, v int) {
idx.Put(k, v)
}

得到以下编译错误: cannot define new methods on non-local type treemap.Map
之后,我将类型别名更改为类型定义:

type IndexType treemap.Map 

func (idx IndexType) Add(k int, v int) {
idx.Put(k, v)
}

现在我开始收到以下错误: idx.Put undefined (type IndexType has no field or method Put) .

最初的想法是我收到此错误是因为 Put是为指针类型定义的,基于这个天真的假设,我更改了接收器类型:

func (idx *IndexType) Add(k int, v int) {
idx.Put(k, v)
}

不编译: idx.Put undefined (type *IndexType has no field or method Put)
尝试了另一种方法:

func (idx IndexType) Add(k int, v int) {
(&idx).Put(k, v)
}

不编译: (&idx).Put undefined (type *IndexType has no field or method Put)
我也试过 type IndexType *treemap.Map但它并没有引导我做任何事情。
我花了几个小时试图理解这些错误背后的逻辑,但我没有找到任何合乎逻辑的解释。

我知道我可以通过使用 embedding 来实现我的目标:

import "github.com/emirpasic/gods/maps/treemap"

type IndexType struct {
*treemap.Map
}

func (idx IndexType) Add(k int, v int) {
idx.Put(k, v)
}

上面的代码编译。

但是,我仍然有一个问题:是否可以扩展 treemap.Map 之类的类型?使用 type运算符(operator)?戈尔

最佳答案

Go spec 中可能说得太清楚了。 :

Each type T has an underlying type: If T is one of the predeclared boolean, numeric, or string types, or a type literal, the corresponding underlying type is T itself. Otherwise, T's underlying type is the underlying type of the type to which T refers in its type declaration.



这意味着当您定义像 type Foo Bar 这样的类型时在哪里 FooBar都是命名类型, Foo 的底层类型是 不是 Bar .是 Bar的基础类型。如果 Barstruct ,然后 Foo的基础类型是定义 Bar 的结构字面量。 (或类型 Bar 是基于的,等等)。由于结构文字没有方法, Foo 也没有。 ; Bar 上定义的方法仅在 Bar 上定义,而不是可能是其基础类型的结构文字。所以 Foo没有方法。
Foo也没有“父类型”;它只有它的底层类型,即结构字面量。没有类型层次结构;你可以 type Foo Bar ,然后 type Baz Foo ,然后 type Qux Baz ,并且这些中没有一个对彼此有任何“知识”;它们只是共享一个底层类型,这只是一个用于存储类型数据的内存布局。

关于go - 类型定义 : Pointer vs Value,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60288848/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com