gpt4 book ai didi

go - 传播时 "Cannot use variable of type []struct as []interface"

转载 作者:数据小太阳 更新时间:2023-10-29 03:39:21 26 4
gpt4 key购买 nike

<分区>

原型(prototype)函数

func test(i ...interface{}) {
// Code here
}

预期用途

type foo struct {
// Fields
}

foos := []foo{
// foo1, foo2 ...
}

test(foos...) // ERROR
test(foos[1], foos[2], ...) // OK

错误

cannot use foos (variable of type []foos) as []interface{} value in argument to test

描述

预期用途是像内置函数一样使用append() .

https://golang.google.cn/pkg/builtin/#append

func append(slice []Type, elems ...Type) []Type

虽然,正如我所见append()不使用 interface{} ,这很奇怪,因为在我搜索过的任何地方,所有人都说使用 interface{}当你不知道类型时。但他们没有。不,append()使用名为 Type 的“内置”类型,显然文档说它是 int .虽然,我不能使用它。没有这种类型。如果有的话,我也不会知道如何使用它。

https://golang.google.cn/pkg/builtin/#Type

type Type int

所以,我在这里很困惑。

问题

  1. 为什么传播运算符没有按预期工作?例如,在 Javascript 中,展开运算符只是将数组展开成项目。但在 Golang 中,它似乎保持相同的数组参数类型,但稍后为编译器提供了传播它的指令。这很奇怪。

  2. 我们是否能够制作类似的自定义机制,如 append()在所有?还是我是个傻瓜,反正我用错了什么?

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