08.无类型常量

本文视频地址

1. Go 常量

使用常量定义的关键字const。Go 中所有与常量有关的声明都使用const。

$GOROOT/src/os/file.go
const (
    // Exactly one of O_RDONLY, O_WRONLY, or O_RDWR must be specified.
    O_RDONLY int = syscall.O_RDONLY // open the file read-only.
    O_WRONLY int = syscall.O_WRONLY // open the file write-only.
    O_RDWR   int = syscall.O_RDWR   // open the file read-write.
    // The remaining values may be or'ed in to control behavior.
    O_APPEND int = syscall.O_APPEND // append data to the file when writing.
    O_CREATE int = syscall.O_CREAT  // create a new file if none exists.
    O_EXCL   int = syscall.O_EXCL   // used with O_CREATE, file must not exist.
    O_SYNC   int = syscall.O_SYNC   // open for synchronous I/O.
    O_TRUNC  int = syscall.O_TRUNC  // truncate regular writable file when opened.
)

上面是准库中的代码通过 const 声明了一组常量。而大多数情况下,Go 常量在声明时并不显式指定类型,也就是说使用的是无类型常量。

// $GOROOT/src/io/io.go
// Seek whence values.
const (
    SeekStart   = 0 // seek relative to the origin of the file
    SeekCurrent = 1 // seek relative to the current offset
    SeekEnd     = 2 // seek relative to the end
)

2. 有类型常量带来的“麻烦”

Go 语言是对类型要求安全的语言。即便两个类型是相同的底层类型(underlying type),但它们仍然是不同的数据类型,所以不可以被相互比较或混在一个表达式中进行运算:

type myString string

var s1 string = "hello"
var s2 myString = "golang"
fmt.Println(s1 + s2)   

在编辑器输入以上代码,会报错:invalid operation: s1 + s2 (mismatched types string and myString)

不同类型的变量间运算时不支持隐式类型转换,要解决上面的编译错误,我们必须进行显式地转型:

type myString string

var s1 string = "hello"
var s2 myString = "golang"
fmt.Println(s1 + string(s2))

image

你可能感兴趣的:(golang)