builtin

int int64 string之间转换

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#stringint  
int,err:=strconv.Atoi(string)
#stringint64
int64, err := strconv.ParseInt(string, 10, 64)
#intstring
string:=strconv.Itoa(int)
#int64string
string:=strconv.FormatInt(int64,10)
```in
# 断言
`value, ok = element.(T)`

demo1
```go
var a interface{}
a = "zhangsan"
// interface{} => string (断言)
a = a.(string)
// 如果直接string(a), 则报错:
cannot convert a (type interface {}) to type string: need type assertion

demo2

1
2
3
4
5
6
7
8
9
10
11
12
13
14
func main() {

for index, element := range list {
if value, ok := element.(int); ok {
fmt.Printf("list[%d] is an int and its value is %d\n", index, value)
} else if value, ok := element.(string); ok {
fmt.Printf("list[%d] is a string and its value is %s\n", index, value)
} else if value, ok := element.(Person); ok {
fmt.Printf("list[%d] is a Person and its value is %s\n", index, value)
} else {
fmt.Println("list[%d] is of a different type", index)
}
}
}

demo3

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
func main() {


for index, element := range list{
switch value := element.(type) {
case int:
fmt.Printf("list[%d] is an int and its value is %d\n", index, value)
case string:
fmt.Printf("list[%d] is a string and its value is %s\n", index, value)
case Person:
fmt.Printf("list[%d] is a Person and its value is %s\n", index, value)
default:
fmt.Println("list[%d] is of a different type", index)
}
}
}