基本資料型別
boolstringint int8 int16 int32 int64uint uint8 uint16 uint32 uint64 uintptrbyte // alias for uint8rune // alias for int32, represents a Unicode code pointfloat32 float64complex64 complex128型別轉化
- Go語言不允許隱式型別轉換
- 別名和原有型別也不能進行隱式型別轉換
不允許隱式型別轉換
package type_testimport "testing"func TestImplicit(t *testing.T) { var a int = 1 var b int64 b = a t.Log(a, b)}輸出
# command-line-arguments_test [command-line-arguments.test]./type_test.go:10:4: cannot use a (type int) as type int64 in assignmentCompilation finished with exit code 2修正后:
func TestImplicit(t *testing.T) { var a int = 1 var b int64 b = int64(a) t.Log(a, b)}輸出
=== RUN TestImplicit--- PASS: TestImplicit (0.00s) type_test.go:12: 1 1PASSProcess finished with exit code 0別名和原有型別也不能進行隱式型別轉換
func TestImplicit(t *testing.T) { var a int = 1 var b int64 b = int64(a) var c MyInt c = b t.Log(a, b, c)}輸出
# command-line-arguments_test [command-line-arguments.test]./type_test.go:13:4: cannot use b (type int64) as type MyInt in assignmentCompilation finished with exit code 2修正后
func TestImplicit(t *testing.T) { var a int = 1 var b int64 b = int64(a) var c MyInt c = MyInt(b) t.Log(a, b, c)}輸出
=== RUN TestImplicit--- PASS: TestImplicit (0.00s) type_test.go:14: 1 1 1PASSProcess finished with exit code 0型別的預定義值
- math.MaxInt64 最大能表示的最大整型
- math.MaxFloat64 最大能表示的浮點型
- math.MaxUint32 最大能表示32位無符號整型
指標型別
- 不支持指標運算
- string是只型別,其默認的初始化值為空字串,而不是nil
不支持指標運算
func TestPoint(t *testing.T) { a := 1 aPtr := &a aPtr = aPtr + 1 t.Log(a, aPtr) t.Logf("%T %T", a, aPtr)}輸出
# command-line-arguments_test [command-line-arguments.test]./type_test.go:20:14: invalid operation: aPtr + 1 (mismatched types *int and int)Compilation finished with exit code 2string是只型別,其默認的初始化值為空字串,而不是nil
func TestString(t *testing.T) { var s string t.Log("*"+s+"*") t.Log(len(s)) if len(s)==0{ t.Log("這是一個空字串") }}輸出
=== RUN TestString--- PASS: TestString (0.00s) type_test.go:27: ** type_test.go:28: 0 type_test.go:30: 這是一個空字串PASSProcess finished with exit code 0
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/54991.html
標籤:Go
