cannot use a (type Integer) as type LessAdder in assignment: Integer does not implement LessAdder (Add method has pointer receiver)
为什么呢?
The method set of any other named type T consists of all methods with receiver type T. The method set of the corresponding pointer type T is the set of all methods with receiver T or T (that is, it also contains the method set of T).
funcFprint(w io.Writer, a ...interface{})(n int, err error)
funcFprintf(w io.Writer, format string, a ...interface{})
funcFprintln(w io.Writer, a ...interface{})
funcPrint(a ...interface{})(n int, err error)
funcPrintf(format string, a ...interface{})
funcPrintln(a ...interface{})(n int, err error)
注意,[]T不能直接赋值给[]interface{}
1
2
3
t := []int{1, 2, 3, 4}
var s []interface{} = t
编译时会输出下面的错误:
cannot use t (type []int) as type []interface {} in assignment
我们必须通过下面这种方式:
1
2
3
4
5
6
7
8
9
t := []int{1, 2, 3, 4}
s := make([]interface{}, len(t))
for i, v := range t {
s[i] = v
}
Type switch与Type assertions
在Go语言中,我们可以使用type switch语句查询接口变量的真实数据类型,语法如下:
1
2
3
switch x.(type) {
// cases
}
x必须是接口类型。来看一个详细的示例:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
package main
import"fmt"
type Stringer interface {
String() string
}
funcextractStr(value interface{})string {
switch str := value.(type) {
casestring:
return str //type of str is string
case Stringer: //type of str is Stringer
return str.String()
default:
return""
}
}
funcmain() {
var str string = "hello world"
res := extractStr(str)
fmt.Println(res)
}
语句switch中的value必须是接口类型,变量str的类型为转换后的类型。
If the switch declares a variable in the expression, the variable will have the corresponding type in each clause. It’s also idiomatic to reuse the name in such cases, in effect declaring a new variable with the same name but a different type in each case.