【问题标题】:How to declare interface array in Go如何在 Go 中声明接口数组
【发布时间】:2014-03-28 15:22:47
【问题描述】:

我很难完成创建接口数组的微不足道的任务。这是我的代码,

var result float64
for i := 0; i < len(diff); i++ {
    result += diff[i]
}
result = 1 / (1 + math.Sqrt(result))

id1 := user1.UserId
id2 := user2.UserId

user1.Similar[id2] = [2]interface{id2, result}
user2.Similar[id1] = [2]interface{id1, result}

result 是浮点数,user*.UserId 是 int。

我的错误信息是

syntax error: name list not allowed in interface type

【问题讨论】:

    标签: arrays interface go


    【解决方案1】:

    例如,

    package main
    
    import (
        "fmt"
    )
    
    func main() {
        x, y := 1, "@"
        a := [2]interface{}{x, y}
        fmt.Println(a)
        b := [2]interface{}{0, "x"}
        fmt.Println(b)
    }
    

    输出:

    [1 @]
    [0 x]
    

    【讨论】:

    • 谢谢。我最终声明了一个结构,因为它始终是 {int, float64} 对,但这是正确的答案!
    猜你喜欢
    • 2014-06-25
    • 2018-01-19
    • 2010-09-24
    • 2015-10-23
    • 2011-09-20
    • 2019-02-15
    • 1970-01-01
    • 2020-02-24
    • 1970-01-01
    相关资源
    最近更新 更多