github.com/zach-klippenstein/go@v0.0.0-20150108044943-fcfbeb3adf58/test/convlit.go (about) 1 // errorcheck 2 3 // Copyright 2009 The Go Authors. All rights reserved. 4 // Use of this source code is governed by a BSD-style 5 // license that can be found in the LICENSE file. 6 7 // Verify that illegal assignments with both explicit and implicit conversions of literals are detected. 8 // Does not compile. 9 10 package main 11 12 // explicit conversion of constants 13 var x1 = string(1) 14 var x2 string = string(1) 15 var x3 = int(1.5) // ERROR "convert|truncate" 16 var x4 int = int(1.5) // ERROR "convert|truncate" 17 var x5 = "a" + string(1) 18 var x6 = int(1e100) // ERROR "overflow" 19 var x7 = float32(1e1000) // ERROR "overflow" 20 21 // implicit conversions merit scrutiny 22 var s string 23 var bad1 string = 1 // ERROR "conver|incompatible|invalid|cannot" 24 var bad2 = s + 1 // ERROR "conver|incompatible|invalid" 25 var bad3 = s + 'a' // ERROR "conver|incompatible|invalid" 26 var bad4 = "a" + 1 // ERROR "literals|incompatible|convert|invalid" 27 var bad5 = "a" + 'a' // ERROR "literals|incompatible|convert|invalid" 28 29 var bad6 int = 1.5 // ERROR "convert|truncate" 30 var bad7 int = 1e100 // ERROR "overflow" 31 var bad8 float32 = 1e200 // ERROR "overflow" 32 33 // but these implicit conversions are okay 34 var good1 string = "a" 35 var good2 int = 1.0 36 var good3 int = 1e9 37 var good4 float64 = 1e20 38 39 // explicit conversion of string is okay 40 var _ = []rune("abc") 41 var _ = []byte("abc") 42 43 // implicit is not 44 var _ []int = "abc" // ERROR "cannot use|incompatible|invalid" 45 var _ []byte = "abc" // ERROR "cannot use|incompatible|invalid" 46 47 // named string is okay 48 type Tstring string 49 50 var ss Tstring = "abc" 51 var _ = []rune(ss) 52 var _ = []byte(ss) 53 54 // implicit is still not 55 var _ []rune = ss // ERROR "cannot use|incompatible|invalid" 56 var _ []byte = ss // ERROR "cannot use|incompatible|invalid" 57 58 // named slice is now ok 59 type Trune []rune 60 type Tbyte []byte 61 62 var _ = Trune("abc") // ok 63 var _ = Tbyte("abc") // ok 64 65 // implicit is still not 66 var _ Trune = "abc" // ERROR "cannot use|incompatible|invalid" 67 var _ Tbyte = "abc" // ERROR "cannot use|incompatible|invalid"