Go Series Tutorial--5. Constant

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed. This is the fifth chapter of our [Golang Series Tutorial] (/SUBJECT/2). # # # defined in the Go language, the term "constant" is used to denote a fixed value. such as ' 5 ', '-89 ', ' I love Go ', ' 67.89 ' and so on. Look at the following code: "' Govar a int = var b string =" I Love Go "" * * in the above code, the variables ' a ' and ' B ' are assigned constant ' 50 ' and ' I Love Go ' * * respectively. The keyword ' const ' is used to denote constants, such as ' 50 ' and ' I love Go '. Even in the above code we don't explicitly use the keyword ' const ', but inside Go, they are constants. As the name implies, a constant cannot be re-assigned to another value. So the following program will not work properly and it will have a compile error: ' cannot assign to a. '. "' Gopackage MainFunc Main () {Const A = 55//Allow A = 89//Do not allow re-assignment} ' [Online Run Program] (HTTPS://PLAY.GOLANG.ORG/P/B2J8_UQOBB) constant value will Determined at compile time. Because a function call occurs at run time, you cannot assign a value to a constant to the return value of a function. "' Gopackage mainimport (" FMT "" math ") func main () {FMT. Println ("Hello, Playground") var a = Math. SQRT (4)//allow const B = Math. SQRT (4)//Not allowed} ' [Run Program Online] (HTTPS://PLAY.GOLANG.ORG/P/DCON1LZCTW) in the program above, because ' a ' is a variable, so we can put the function ' math. The return value of SQRT (4) is assigned to it (we will discuss the function in detail in a separate place). ' B ' is a constant whose value needs to be determined at compile time. function ' Math. SQRT (4) ' is calculated only at run time, so ' const B = Math '. SQRT (4) ' will throw errors ' error main.go:11:const initializer math. SQRT (4) is not a constant) ' # # # string constant any value in double quotes is GThe string constant in the O. Strings such as ' Hello world ' or ' Sam ' are constants in Go. What types of strings belong to constants? The answer is that they are of no type. string constants such as ' Hello world ' do not have any type. "' Goconst hello = ' Hello world ' above example, we assign ' Hello World ' to the constant ' hello '. Are there any types of constant ' hello ' now? The answer is no. Constants still have no type. Go is a strongly typed language, and all variables must have a definite type. So, how does the following program assign an untyped constant ' Sam ' to the variable ' name '? "' Gopackage mainimport (" FMT ") func main () {var name =" Sam "FMT. Printf ("type%T value%v", Name, Name)} "[Running Program Online] (https://play.golang.org/p/xhYV4we_Jz) * * The answer is that there is an untyped constant with a default type associated with them. and provide it only if one line of code is needed. In the declaration ' var name = ' Sam ', ' name ' requires a type, which is obtained from the default type of the string constant ' Sam '. * * Is there a way to create a constant with a type? The answer is yes. The following code creates a typed constant. ' ' goconst typedhello string = ' Hello world ' in the code above, ' Typedhello ' is a ' string ' type of constant. Go is a strongly typed language, and mixed types are not allowed during the allocation process. Let's take a look at the following procedure to see what this sentence means. "' Gopackage MainFunc Main () {var defaultname =" Sam "//Allow type myString string var customname myString =" Sam "//Allow CU Stomname = defaultname//Not allowed} ' [Run Program Online] (https://play.golang.org/p/1Q-vudNn_9) in the above code, we first create a variable ' defaultname ' and assign a constant ' Sam '. * * The default type of the constant ' Sam ' is ' string ', so theThe value ' DefaultName ' is the ' string ' type. * * Next line, we will create a new type ' myString ', which is the alias of ' string '. Then we create a ' myString ' variable ' customname ' and assign him a constant ' Sam '. Because the constant ' Sam ' is untyped, it can be assigned to any string variable. So this assignment is allowed, and the ' Customname ' type is ' myString '. Now, we have a variable of type ' string ' ' DefaultName ' and another variable of type ' myString ' customname '. Even though we know that this ' myString ' is a ' string ' type of alias. Go type policy does not allow a variable of one type to be assigned to a variable of another type. So assigning ' defaultname ' to ' customname ' is not allowed, and the compiler throws an error ' Main.go:7:20:cannot use DefaultName (type string) as type myString I N Assignmen '. # # # Boolean constant Boolean constant and string constant are no different. They are two untyped constants of ' true ' and ' false '. The rules for string constants apply to Boolean constants, so we don't repeat them here. The following is a simple procedure for interpreting Boolean constants. "' Gopackage MainFunc Main () {Const TRUECONST = True Type mybool bool var defaultbool = trueconst//allow Var custombool my Bool = trueconst//Allow Defaultbool = custombool//Not allowed} ' [Online Run Program] (Https://play.golang.org/p/h9yzC6RxOR) The above program is self-explanatory. # # # Numeric constant numeric constants contain constants for integers, floating-point numbers, and complex numbers. There are some subtleties in the numeric constants. Let's look at some examples to make it clear. "' Gopackage mainimport (" FMT ") func main () {Const A = 5 var intvar int = a var int32var int32 = a var float64var float64 = a var cOmplex64var complex64 = a fmt. Println ("Intvar", Intvar, "\nint32var", Int32var, "\nfloat64var", Float64var, "\ncomplex64var", Complex64var)} "[ Online Run Program] (Https://play.golang.org/p/a8sxVNdU8M) above the program, the constant ' a ' is no type, its value is ' 5 '. You might want to know what the default type of ' a ' is, and if it does have one, then how do we assign it to different types of variables. The answer lies in the syntax of ' a '. The following program will make things clearer. "' Gopackage mainimport (" FMT ") func main () {var i = 5 var f = 5.6 var c = 5 + 6i FMT. Printf ("I ' s type%T, F ' s type%T, C ' s type%T", I, F, c)} ' [Online Run Program] (https://play.golang.org/p/kJq69Vpqit) in the above program, the type of each variable is determined by the syntax of the numeric constants. ' 5 ' is an integer in the syntax, ' 5.6 ' is a floating-point number, and the syntax of ' 5+6i ' is plural. When we run the above program, it will print out ' i ' type int, f ' s type float64, C ' s type complex128 '. Now I hope the following program will work correctly. "' Gopackage mainimport (" FMT ") func main () {Const A = 5 var intvar int = a var int32var int32 = a var float64var float64 = a var Complex64var complex64 = a fmt. Println ("Intvar", Intvar, "\nint32var", Int32var, "\nfloat64var", Float64var, "\ncomplex64var", Complex64var)} "[ Online Run Program] (HTTPS://PLAY.GOLANG.ORG/P/_ZU0IK-HYJ) In this program, the value of ' a ' is ' 5 ', the syntax of ' a ' is generic (it can represent aA floating-point number, an integer, or even a complex number that has no imaginary part, so that it can be assigned to any compatible type. The default types of these constants can be thought of as being generated from the context in the run. ' var intvar int = A ' requires ' a ' is ' int ', so it becomes an ' int ' constant. ' var complex64var complex64 = A ' requires ' a ' is ' complex64 ', so it becomes a plural type. Very simple:). # # # Numeric Expression numeric constants can be freely mixed and matched in an expression, and only required if they are assigned to a variable or used anywhere in the code that requires the type. "' Gopackage mainimport (" FMT ") func main () {var a = 5.9/8 fmt. Printf ("A ' s type%T value%v", A, a)} ' [Online Run Program] (Https://play.golang.org/p/-8i-iX-jIG) in the above program, ' 5.9 ' is a floating-point type in the syntax, ' 8 ' is the integer type, ' 5.9/8 ' is allowed because two is a numeric constant. The result of division is that ' 0.7375 ' is a floating-point type, so the type of ' a ' is floating-point type. The output of this program is: ' A ' s type float64 value 0.7375 '. * * Previous tutorial-[type] (https://studygolang.com/articles/11869) * * * Next tutorial-[functions] (https://studygolang.com/articles/11892) * *

via:https://golangbot.com/constants/

Author: Nick Coghlan Translator: Guoxiaopang proofreading: polaris1119

This article by GCTT original compilation, go language Chinese network honor launches

This article was originally translated by GCTT and the Go Language Chinese network. Also want to join the ranks of translators, for open source to do some of their own contribution? Welcome to join Gctt!
Translation work and translations are published only for the purpose of learning and communication, translation work in accordance with the provisions of the CC-BY-NC-SA agreement, if our work has violated your interests, please contact us promptly.
Welcome to the CC-BY-NC-SA agreement, please mark and keep the original/translation link and author/translator information in the text.
The article only represents the author's knowledge and views, if there are different points of view, please line up downstairs to spit groove

3,683 reads ∙1 likes
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.