4.Go by Example: Constants

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

Go supports constants of character, string, boolean, and numeric values.

const declares a constant value.

A const statement can appear anywhere a var statement can.

Constant expressions perform arithmetic with arbitrary precision.

A numeric constant has no type until it’s given one, such as by an explicit cast.


A number can be given a type by using it in a context that requires one, such as a variable assignment or function call. For example, here math.Sin expects a float64.


package mainimport "fmt"import "math"const s string = "constant"func main() {    fmt.Println(s)     const n = 500000000     const d = 3e20 / n    fmt.Println(d)     fmt.Println(int64(d))    fmt.Println(math.Sin(n))}


譯:
Go 語言支援的常量類型有 characer string 字元型 boolean 波爾型 numeric 數值


用 const關鍵字來聲明一個常量值


一個常量聲明能展現的 、任何一個var聲明的都可以

常量運算式可以展現任意精度的算術運算


一個算術運算式可以沒有類型,直到他被給予一個值,例如通過顯示轉換


一個數可以用它在需要使用一個給定的類型,例如一個變數的賦值或者一個函數的調用。

例如,這裡的math.Sin就是期望是一個float64的類型。

package mainimport "fmt"import "math"const s string = "constant"func main() {    fmt.Println(s)     const n = 500000000 //定義一個常量 注意這裡的常量類型就是不允許改變了         const d = 3e20 / n   //根據科學技術法計算    fmt.Println(d)     fmt.Println(int64(d))    fmt.Println(math.Sin(n))}

運行結果
$ go run constant.go 
constant
6e+11
600000000000
-0.28470407323754404

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.