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

传播时“不能将[] 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?

  • 写回答

1条回答 默认 最新

  • dongying2112 2019-09-02 06:30
    关注

    I think that this is the issue that you are running into here.

    https://github.com/golang/go/wiki/InterfaceSlice

    I am not an expert in this but have hit this before, the "slice of empty interface" is not an interface and therefore cannot be replaced by any type which is the issue that you are having, it has to do with the memory structure being different. The above has a far better explanation than one that I can give.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥15 请问Lammps做复合材料拉伸模拟,应力应变曲线问题
  • ¥30 python代码,帮调试
  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥100 Jenkins自动化部署—悬赏100元