关于golang:08无类型常量

15次阅读

共计 1235 个字符,预计需要花费 4 分钟才能阅读完成。

本文视频地址

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))

正文完
 0