douanrang4728
2019-09-02 00:34
浏览 193
已采纳

传播时“不能将[] struct类型的变量用作[]接口”

Prototype function

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

Intended use

type foo struct {
    // Fields
}

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

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

Error

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

Description

The intended use is to be used like the built-in function append().

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

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

Although, as I've seen append() doesn't use interface{}, which is strange, since anywhere that I searched all people say to use interface{} when you don't know the type. But they don't. Nope, append() uses a "build-in" type called Type, which apparently the docs say that it's a int. Although, I cannot use it. There isn't such type. And neither I would know how to use it if there was.

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

type Type int

So, I'm very confused here.

Questions

  1. Why does the spread operator not work as intended? For example, in Javascript the spread operator just spreads the array into items. But in Golang it seems like it keeps the same array parameter type as it is but gives the compiler later an instruction to spread it. Which is odd.

  2. Are we even able to make similar custom mechanisms like append() at all? Or am I a dummy and I'm using something wrong anyway?

图片转代码服务由CSDN问答提供 功能建议

原型功能</ strong> </ p>

  func test(i ... interface {}){
 //此处编码
} 
 </ code> </ pre> 
 
 

预期用途</ strong> </ p>

  type foo struct {
 //字段
} 
 
foos:= []  foo {
 // foo1,foo2 ... 
} 
 
test(foos ...)// ERROR 
test(foos [1],foos [2],...)// OK 
  </ code> </ pre> 
 
 

错误</ strong> </ p>

不能使用foos([] foos类型的变量) 作为测试参数中的[] interface {}值</ p> </ blockquote>

说明</ h1>

-in函数 append()</ code>。</ p>

https://golang.google.cn/pkg/builtin/#append </ p>

  func append(slice [] Type,elems ... 类型)[]类型
 </ code> </ pre> 
 
 

不过,正如我所见, append()</ co de>不使用 interface {} </ code>,这很奇怪,因为在我搜索过的任何地方,当您不知道类型时,所有人都会说要使用 interface {} </ code>。 但是他们没有。 不, append()</ code>使用一种称为“ Type </ code>”的“内置”类型,显然,文档称这是 int < /代码>。 虽然,我不能使用它。 没有这种类型。 </ p>

https://golang.google.cn/pkg/builtin/#Type </ p>

  type类型int 
 </ code> </ pre>  
 
 

所以,我在这里很困惑。 </ p>

问题</ h1>
  1. 为什么扩展运算符不能按预期工作? 例如,在Javascript中,spread运算符只是将数组扩展为项目。 但是在Golang中,它似乎保持了与相同的数组参数类型</ strong>,但是稍后向编译器提供了扩展它的指令。 </ p> </ li>

  2. 我们什至完全能够做出类似 append()</ code>这样的自定义机制吗? 还是我是个假人,反正使用了错误的东西?</ p> </ li> </ ol> </ div>

1条回答 默认 最新

相关推荐 更多相似问题