【问题标题】:Go change from interface to required type从接口更改为所需类型
【发布时间】:2019-09-07 18:24:26
【问题描述】:

我有这个方法,我收到一个int64 参数。该参数在某些领域使用,然后应该被传递给另一个需要不同类型的方法(来自外部库):type AcctInterimInterval uint32

我尝试将其转换为 uint32,但脚本抱怨它:invalid type assertion: ... (non-interface type int on left)

我也尝试将其转换为AcctInterimInterval,但这次出现了不同的错误:interface conversion: interface {} is int, not main.AcctInterimInterval

这是我目前的测试代码:

package main

import (
    "fmt"
)

//  defined in some other lib
type AcctInterimInterval uint32

//  defined in some other lib
func test(value AcctInterimInterval){
    fmt.Println(value)
}

func main() {
    //  int received externally
    interval := 60

    var acctInterval interface{} = interval

    test(acctInterval.(AcctInterimInterval))
}

相关游乐场:https://play.golang.org/p/tTW5J2FIAy3

【问题讨论】:

    标签: go types type-assertion


    【解决方案1】:

    您的acctInterval 变量包含int 值,因此您只能从中获取type-assertint

    acctInterval.(int)
    

    然后你可以convertAcctInterimInterval

    test(AcctInterimInterval(acctInterval.(int)))
    

    Go Playground 上试试。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-11-18
      • 1970-01-01
      • 1970-01-01
      • 2014-03-05
      • 2018-08-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多