1

Go类型转换

 2 years ago
source link: https://davidchan0519.github.io/2019/08/15/golang-type-cast/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Go类型转换

Posted on

2019-08-15

| Views: 74

go语言同C/C++一样,可以在不同的类型间使用类型强制转换。

基本用法:

type A int32
type B int32

a := A{100}

//type cast
b := B(a)

上述代码,将类型为A的值a强制转换为类型为B的值b。但是这有一个前提条件:即A和B的底层类型一样。所谓的底层类型就是在声明A和B类型的时候,所指代的原始类型。两者都是int32,所以一样,故可以转换。如果底层类型不一样,则编译会报错。

读者不妨试试下面的例子:

package main
import ( "fmt")
type Meter struct
{
Value int64
}
type Centimeter struct {
Value int64
}

func main() {
cm := Centimeter{
Value:100,
}
var m Meter
m = Meter(cm) //cast Centimer to Meter
fmt.Println("meter:",m.Value)
cm = Centimeter(m)//cast Meter to Centimer
fmt.Println("centimeter:",cm.Value)}

meter: 100
centimeter: 100

如果将centimeter的value类型变为int32,编译程序会报错

src\base\type_usage.go:21:11: cannot convert cm (type Centimeter) to type Meter
src\base\type_usage.go:24:17: cannot convert m (type Meter) to type Centimeter

您的鼓励是我持之以恒的动力

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK