go中的常量

來源:互聯網
上載者:User
這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。

轉自:http://segmentfault.com/q/1010000002472534

package main

import (

    "fmt"

    "reflect"

)


const (

    cmask  = 127

)


func main() {

    var u uint8

    u = 22

    r1 := u + cmask

    fmt.Println(r1)

    fmt.Println(reflect.TypeOf(cmask)) // int

    //------------------

    mask := 0x7f

    //r2 := u + mask

    //fmt.Println(r2)

    fmt.Println(reflect.TypeOf(mask)) // int

}

cmask 和 mask 反射出來的類型都是 int。為什麼 cmask 可以和u進行操作,而 mask 不行 ???


huandu:

原因詳見 Go 的文法說明:

If the expression values are untyped constants, the declared constants remain untyped and the constant identifiers denote the constant values.

換人話來說就是:使用沒指定類型的 const,就相當於直接使用它對應的常量。

所以你寫 u + cmask 就相當於寫了 u + 127,於是不會儲存。而 mask 是個普通變數,沒有這種特殊待遇,類型是在聲明時就固定了(int),因此會因為 int 和 uint8 不相容而報錯。


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.