08.无类型常量
使用常量定义的关键字const。Go 中所有与常量有关的声明都使用const。
<pre><code class="lang-go hljs">$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. )</code></code></pre>上面是准库中的代码通过 const 声明了一组常量。而大多数情况下,Go 常量在声明时并不显式指定类型,也就是说使用的是无类型常量。
<pre><code class="lang-go hljs">// $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 )</code></code></pre><h1>2. 有类型常量带来的“麻烦”</h1>Go 语言是对类型要求安全的语言。即便两个类型是相同的底层类型(underlying type),但它们仍然是不同的数据类型,所以不可以被相互比较或混在一个表达式中进行运算:
<pre><code class="lang-go hljs">type myString string var s1 string = "hello" var s2 myString = "golang" fmt.Println(s1 s2) </code></code></pre>在编辑器输入以上代码,会报错:invalid operation: s1 s2 (mismatched types string and myString)
不同类型的变量间运算时不支持隐式类型转换,要解决上面的编译错误,我们必须进行显式地转型:
<pre><code class="lang-go hljs">type myString string var s1 string = "hello" var s2 myString = "golang" fmt.Println(s1 string(s2))</code></code></pre><span class="img-wrap"></span>
到此这篇关于“08.无类型常量”的文章就介绍到这了,更多文章或继续浏览下面的相关文章,希望大家以后多多支持JQ教程网!
您可能感兴趣的文章:
java入门篇-数据类型
Python你知道多少?教你玩转Python变量与常量!
C#泛型全面讲解
java常量与变量的学习笔记
mysql 数据库unsigned的用法
php变量与常量-php入门教程(2)
php支持哪8种数据类型?
08.无类型常量
Go语言入门基础(一)
php中static,const与define的区别分析