从界面更改为所需类型
Go change from interface to required type
我有这个方法,我收到一个 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))
}
您的 acctInterval
变量包装了一个 int
值,因此您只能从中 type-assert 一个 int
:
acctInterval.(int)
然后你可以 convert 到 AcctInterimInterval
:
test(AcctInterimInterval(acctInterval.(int)))
在 Go Playground 上试用。
我有这个方法,我收到一个 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))
}
您的 acctInterval
变量包装了一个 int
值,因此您只能从中 type-assert 一个 int
:
acctInterval.(int)
然后你可以 convert 到 AcctInterimInterval
:
test(AcctInterimInterval(acctInterval.(int)))
在 Go Playground 上试用。