How to declare interface array in Go

huangapple go评论121阅读模式
英文:

How to declare interface array in Go

问题

我在创建一个接口数组的简单任务中遇到了困难。以下是我的代码:

  1. var result float64
  2. for i := 0; i < len(diff); i++ {
  3. result += diff[i]
  4. }
  5. result = 1 / (1 + math.Sqrt(result))
  6. id1 := user1.UserId
  7. id2 := user2.UserId
  8. user1.Similar[id2] = [2]interface{id2, result}
  9. user2.Similar[id1] = [2]interface{id1, result}

其中result是一个float64类型,user*.UserId是一个int类型。

我的错误信息是:

语法错误:接口类型中不允许使用名称列表

英文:

I am having difficulty in what should be a trivial task of creating an interface array. Here is my code,

  1. var result float64
  2. for i := 0; i &lt; len(diff); i++ {
  3. result += diff[i]
  4. }
  5. result = 1 / (1 + math.Sqrt(result))
  6. id1 := user1.UserId
  7. id2 := user2.UserId
  8. user1.Similar[id2] = [2]interface{id2, result}
  9. user2.Similar[id1] = [2]interface{id1, result}

result is a float and user*.UserId is an int.

My error message is

syntax error: name list not allowed in interface type

答案1

得分: 7

例如,

  1. package main
  2. import (
  3. "fmt"
  4. )
  5. func main() {
  6. x, y := 1, "@"
  7. a := [2]interface{}{x, y}
  8. fmt.Println(a)
  9. b := [2]interface{}{0, "x"}
  10. fmt.Println(b)
  11. }

输出:

  1. [1 @]
  2. [0 x]
英文:

For example,

  1. package main
  2. import (
  3. &quot;fmt&quot;
  4. )
  5. func main() {
  6. x, y := 1, &quot;@&quot;
  7. a := [2]interface{}{x, y}
  8. fmt.Println(a)
  9. b := [2]interface{}{0, &quot;x&quot;}
  10. fmt.Println(b)
  11. }

Output:

  1. [1 @]
  2. [0 x]

huangapple
  • 本文由 发表于 2014年2月26日 10:31:58
  • 转载请务必保留本文链接:https://go.coder-hub.com/22030541.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定