cannot convert (type interface {}) to type int: need type assertion
問題:
在使用interface表示任何型別時,如果要將interface轉為某一型別,直接強制轉換是不行的,例如:
var t interface{} = "abc"
s := string(t)
1
2
3
4
cannot convert t(type interface {}) to type string: need type assertion
golang 任何型別interface{}
cannot convert (type interface {}) to type int: need type assertion
golang中可以使用interface{}表示任何型別。
本文以例子的形式,演示interface{}的使用。
example1
package main
import (
"fmt"
)
func main() {
var t1 interface{} = 2
v, ok := t1.(int)
if ok {
fmt.Println("int:", v)
} else {
fmt.Println("v:", v)
}
}
- output:
$ ./test
int: 2
判斷interface的型別,如果是int型,就輸出介面表示的值。
有時,如果確定知道型別T(例如int),會直接使用如下方式進行斷言:
v := t1.(int)
- 1
但斷言失敗,會panic。可根據具體情況選擇使用哪種方式。
example2
package main
import (
"fmt"
)
func main() {
var t1 interface{} = "abc"
switch v := t1.(type) {
case int:
fmt.Println("int:", v)
case string:
fmt.Println("string:", v)
default:
fmt.Println("unknown type:", v)
}
}
如果t1為abc:
output:
$ ./test
string: abc
如果t1為23:
output:
$ ./test
int: 23
如果t1為1.2
output:
$ ./test
unknown type: 1.2
更多interface的參考
相關文章
- Golang Cannot use ss(type AAA) as type AAA in map indexGolangIndex
- The type List is not generic; it cannot …
- Cannot infer type arguments for PageImpl
- Cannot set property ‘type‘ of null(vue)NullVue
- 【區分】Typescript 中 interface 和 typeTypeScript
- java.lang.IllegalArgumentException: Cannot convert value of type [$Proxy7 implemJavaException
- 'int32_t' does not name a type
- golang使用sqlx報錯:unsupported type []interface {}, a slice of interfaceGolangSQL
- xxx cannot be resolved to a type
- variable: Type 與 Type variable
- TypeScript 裡 interface 和 type 的區別TypeScript
- ts中的type 和 interface 區別
- TypeScript中,type、interface、class的區別TypeScript
- Value Type vs Reference Type in SwiftSwift
- C# convert sql blob type to plain stringC#SQLAI
- error: invalid type argument of unary ‘*‘ (have ‘int‘) *__first = __tmp;Error
- Type in Chakra
- HITSC_4_Data Type and Type Checking
- A resource type with the name 'ora.daemon.type' is already registered
- oracle enqueue typeOracleENQ
- jQuery.type()jQuery
- oracle block type!OracleBloC
- Type classes in Scala
- block corruption typeBloC
- [PLT] Type system
- The type MultipartEntity is deprecated
- Type與Class
- MIME TYPE (轉)
- requirement for output typeUIREM
- type.jsJS
- 解決 TypeError: Type aliases cannot be used with isinstance(). 辦法Error
- TypeScript中,interface和type使用上有什麼區別?TypeScript
- Python-unsupported operand type(s) for %: 'builtin_function_or_method' and 'int'PythonUIFunction
- Cannot convert value of type [com.sun.proxy.$Proxy11 implementing com.xuyp.managize.service.IBaseSer
- 解決java.lang.IllegalArgumentException: 'Content-Type' cannot contain wildcard type '*'異常(真實有效)...JavaExceptionAI
- Typescript 中的 interface 和 type 到底有什麼區別TypeScript
- Blob type 屬性
- File type 屬性