Basic go syntax

Source: Internet
Author: User
Packages

Each go program is composed of packages.

The entry for running the program is 'main '.

This program uses and imports the package"fmt"And '"Math/Rand "'.

By convention, the package name is the same as the last directory in the import path. For example, the '"Math/Rand"' Package is composedpackage randStatement.

Note:The running environment of this program is fixed, sorand.IntnAlways Returns the same number. (To get different numbers, you need to generate different seed numbers. For more information, seerand.Seed.)

 

package mainimport ("fmt""math/rand")func main() {fmt.Println("My favorite number is", rand.Intn(10))}

 

Import

This Code combines the import with parentheses. This is the "factored" Import Statement. You can also write multiple import statements, for example:

import "fmt"import "math"

package mainimport ("fmt""math")func main() {fmt.Printf("Now you have %g problems.",math.Nextafter(2, 3))}

 

Export Name

After importing a package, you can call it with the exported name.

In go, the upper-case names are exported.

FooAndFOOAre exported names. NamefooIs not exported.

Run the code. Thenmath.piRenamedmath.PiTry again.

 

package mainimport ("fmt""math")func main() {fmt.Println(math.pi)}
Function

A function can have no or multiple parameters.

In this example, 'add' accepts twointType parameter.

Note that the type is after variable name _.

(Refer to this article on the definition of Go syntax to learn why types appear in this form .)

package mainimport "fmt"func add(x int, y int) int {return x + y}func main() {fmt.Println(add(42, 13))}
Function (continued)

When two or more consecutive function naming parameters are of the same type, the parameter can be omitted except for the last type.

In this example,

x int, y int

Abbreviated

x, y int
package mainimport "fmt"func add(x, y int) int {return x + y}func main() {fmt.Println(add(42, 13))}
Multi-value return

The function can return any number of returned values.

This function returns two strings.

package mainimport "fmt"func swap(x, y string) (string, string) {return y, x}func main() {a, b := swap("hello", "world")fmt.Println(a, b)}

 

Name Return Value

The function accepts parameters. In go, a function can return multiple "result Parameters", not just a value. They can be named and used as variables.

If the return value parameter is namedreturnStatement, the current value is returned as the return value.

package mainimport "fmt"func split(sum int) (x, y int) {x = sum * 4 / 9y = sum - xreturn}func main() {fmt.Println(split(17))}

 


Variable

varThe statement defines a list of variables. Similar to the parameter list of a function, the type is later.

package mainimport "fmt"var i intvar c, python, java boolfunc main() {fmt.Println(i, c, python, java)}

 

Initialize variable

A variable definition can contain an initial value. Each variable corresponds to one.

If the expression is used for initialization, the type can be omitted. The variable obtains the type from the initial value.

package mainimport "fmt"var i, j int = 1, 2var c, python, java = true, false, "no!"func main() {fmt.Println(i, j, c, python, java)}

 

Short declaration variable

In a function, the ': =' concise value assignment statement is of a specific type and can be used to replacevarDefinition.

Each syntax block outside the function must start with a keyword ('var ', 'func', and so on), and The': = 'structure cannot be used outside the function.

package mainimport "fmt"func main() {var i, j int = 1, 2k := 3c, python, java := true, false, "no!"fmt.Println(i, j, k, c, python, java)}
Basic Type

The basic types of go are basic types.

Boolstringint int8 int16 int32 int64uint uint8 uint16 uint64 uintptrbyte // uint8 alias Rune // int32 alias // represents a unicode code float32 float64complex64 complex128

package mainimport ("fmt""math/cmplx")var (ToBe   bool       = falseMaxInt uint64     = 1<<64 - 1z      complex128 = cmplx.Sqrt(-5 + 12i))func main() {const f = "%T(%v)\n"fmt.Printf(f, ToBe, ToBe)fmt.Printf(f, MaxInt, MaxInt)fmt.Printf(f, z, z)}
Type conversion

ExpressionT(v)Set the valuevConvert to type 'T '.

Some numerical conversions:

var i int = 42var f float64 = float64(i)var u uint = uint(f)

Or, in a simpler form:

i := 42f := float64(i)u := uint(f)

Different from C, the explicit conversion is required for assigning values to different types of Go projects. Try removing the examplefloat64OrintTo see what will happen.

package mainimport ("fmt""math")func main() {var x, y int = 3, 4var f float64 = math.Sqrt(float64(x*x + y*y))var z int = int(f)fmt.Println(x, y, z)}

 

Constant

The definition of a constant is similar to that of a variable, except thatconstKeyword.

A constant can be a character, String, Boolean, or numeric value.

Constants cannot be used.:=Syntax definition.

Package mainimport "FMT" const Pi = 3.14 func main () {const world = "world" FMT. println ("hello", World) FMT. println ("happy", PI, "day") const truth = truefmt. println ("Go rules? ", Truth )}
Numerical constant

A numerical constant is a high-precision _ value _.

A constant of unspecified types is determined by context.

Try the output.needInt(Big)Right.

package mainimport "fmt"const (Big   = 1 << 100Small = Big >> 99)func needInt(x int) int { return x*10 + 1 }func needFloat(x float64) float64 {return x * 0.1}func main() {fmt.Println(needInt(Small))fmt.Println(needFloat(Small))fmt.Println(needFloat(Big))}

 

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.