gpt4 book ai didi

函数参数中的多态性

转载 作者:IT王子 更新时间:2023-10-29 02:16:59 26 4
gpt4 key购买 nike

我发现了几个标题相似的问题,但在其中找不到我的问题的答案:

我有以下简单场景:

类型:

    type intMappedSortable interface {
getIntMapping() int
}

type Rectangle struct {
length, width int
}

func (r Rectangle) getIntMapping() int {
return r.Area();
}

func (Rectangle r) getIntMapping() int {
return r.length * r.width;
}

主要内容:

func main() {
r := rand.New(rand.NewSource(time.Now().UnixNano()))

var values []int
values = make([]int, 0)

for i := 0; i < 10; i++ {
values = append(values, r.Intn(20))
}

var rects []Rectangle;
rects = make([]intMappedSortable, len(values));

for i,v:= range values {
r := Rectangle{v,v};
rects[i] = r;
}
for i,v:= range rects {
fmt.Println(v.Area());
}


rectsRet := make(chan intMappedSortable, len(rects));
sort(rects, rectsRet);
}

工作:

func sort(values []intMappedSortable, out chan intMappedSortable) {...}

我如何设法将矩形传递给排序函数,然后在它之后的 main 中处理排序后的矩形?

我试过:

var rects []*Rectangle;
rects = make([]*Rectangle, len(values));

作为我 C 时代的习惯,我不想复制矩形,只复制地址,所以我可以直接在原始 slice 中排序,避免对整个数据进行 2 次复制过程。

失败后我尝试了:

var rects []intMappedSortable;
rects = make([]*Rectangle, len(values));

我了解到 Go 通过持有指向未公开的原始数据的指针来处理“多态性”,所以我将 *Rectangle 更改为 Rectangle,两者都给了我 Rectangle 不是 []intMappedSortable 的编译器错误

显然有效的是:

var rects []intMappedSortable;
rects = make([]intMappedSortable, len(values));

for i,v:= range values {
r := Rectangle{v,v};
rects[i] = r;
}

但是这些矩形现在是被复制了,还是只是复制了它们的引用的接口(interface)的内存表示?此外,现在无法访问矩形的长度和宽度,因为 slice 不再是明确的矩形类型。

那么,我将如何实现这种情况?我想创建一个实现 mapToInt() 的任何结构的 slice ,对 slice 进行排序,然后在它之后继续使用具体类型

编辑/跟进:

我知道它的风格不好,但我正在尝试:

我能以某种方式对动态类型使用类型断言吗:

func maptest(values []intMappedSortable, out interface{}) {
oType := reflect.TypeOf(out);
fmt.Println(oType); // --> chan main.intMappedSortable
test := values[0].(oType) //i know this is not working AND wrong even in thought because oType holds "chan intMappedSortable", but just for theory's sake
}

我怎么能这样做,或者这是不可能的。我不是说它是否“注定要完成”,我知道它不是。但是这可能吗?^^

最佳答案

But are are these rectangles now copied or is just the memory representation of the interface with their reference copied?

后者,见“what is the meaning of interface{} in golang?

An interface value is constructed of two words of data:

  • one word is used to point to a method table for the value’s underlying type,
  • and the other word is used to point to the actual data being held by that value.

I want to create a slice of ANY structure, that implements the mapToInt(), sort the slice and then keep working with the concrete type after it

这是不可能的,因为 Go 中没有通用性。
参见“What would generics in Go be?

这就是为什么你有像“gen”这样的项目:

generates code for your types, at development time, using the command line.
gen is not an import; the generated source becomes part of your project and takes no external dependencies.

关于函数参数中的多态性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25447079/

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