1. Variables and constants
Identifiers and keywords in Golang
Identifier
In Go, identifiers are composed of alphanumeric and _ (underscore) and can only start with letters and _. To give a few examples:abc, _, _123, a123
。
Keywords
Neither keyword nor reserved word is recommended as variable names:
There is a Go language25 keywords:
break default func interface select case defer go map struct chan else goto package switch const fallthrough if range type continue for import return var
In addition, there are also37 reserved words.
Constants: true false iota nil Types: int int8 int16 int32 int64 uint uint8 uint16 uint32 uint64 uintptr float32 float64 complex128 complex64 bool byte rune string error Functions: make len cap new append copy close delete complex real imag panic recover
Variables in Golang
Each variable in the Go language has its own type, and the variable must be declared before it can be used. Duplicate declarations are not supported within the same scope.And it must be used after the Go language variable is declared.
Standard Statement
The variable declaration format of Go language is: (Recommended camel nomenclature for variable declaration in Golang)
Variable declaration with keywordsvar
At the beginning, the variable type is placed after the variable, and no semicolon is required at the end of the line. For example:
var Variable name Variable Type
Batch statement
Each variable declared requires writingvar
Keywords will be more cumbersome, and batch variable declarations are also supported in go language:
var name string var age int var flag bool
Initialization of variables
When Go declares variables, it will automatically initialize the memory area corresponding to the variable. Each variable is initialized to the default value of its type, for example:The default values for integer and floating point variables are0
。 The default value of string variables isEmpty string
. Boolean variables default tofalse
。 The default for slices, functions, and pointer variables isnil
。
Of course, we can also specify the initial value for the variable when declaring it. The standard format for variable initialization is as follows:
var Variable name type = expression
For example:
var name string = "csp" var age int = 22
Or initialize multiple variables at once
var name, age = "csp", 22
Type derivation (automatically judge the type of variable based on the value)
Sometimes we omit the type of the variable. At this time, the compiler will deduce the type of the variable based on the value on the right side of the equal sign to complete the initialization.
var name = "csp" //Automatically recognized as stringvar age = 18 //Automatically recognized as int
Short variable declaration
Inside the function, a simpler:=
declare and initialize variables.
package main import "fmt" // Global variable mvar m = 100 func main() { n := 10 m := 200 // Declare the local variable m here (m, n) }
Anonymous variables
When using multiple assignments, if you want to ignore a value, you can useanonymous variable.
Anonymous variables are represented by an underscore, for example:
func foo() (int, string) { return 10, "csp" } func main() { x, _ := foo() //Receive only the first return value of the foo function _, y := foo() //Receive only the second return value of the foo function ("x=", x) ("y=", y) }
Anonymous variables do not occupy namespace and do not allocate memory, so there is no duplicate declaration between anonymous variables.. (existLua
In programming languages, anonymous variables are also called dumb variables. )
Notes:
- Every statement outside the function must start with a keyword (var, const, func, etc.)
-
:=
Cannot be used outside the function. -
_
It is mostly used for placeholding, indicating that the value is ignored.
Constants in Golang
Compared with variables, constants are constant values, which are mostly used to define values that will not change during the program's run. The declaration of constants is very similar to the declaration of variables, justvar
Change it toconst
, constants must be assigned values when defined.
const pi = 3.1415 const e = 2.7182
After declaring the two constants pi and e, their values can no longer change during the entire program run.
Multiple constants can also be declared together:
const ( pi = 3.1415 e = 2.7182 )
When const declares multiple constants at the same time, if the value is omitted, it means that the value is the same as the above line. For example:
const ( n1 = 100 n2 n3 )
In the above example, constantsn1、n2、n3
The values are all 100.
iota constant counter in Golang
iota
It is a constant counter of Go language.Only used in constant expressions。
iota
In the const keywordIt will be reset to 0 when it appears. ConstEach new row of constant declaration will makeiota
Counting is accumulated once(iota can be understood as the row index in the const statement block). Using iota can simplify definitions and is useful when defining enumerations.
For example:
const ( n1 = iota //0 n2 //1 n3 //2 n4 //3 )
Several common
iota
Example
use_
Skip certain values
const ( n1 = iota //0 n2 //1 _ n4 //3 )
iota
statementIn the middle of the line
const ( n1 = iota //0 n2 = 100 //100 n3 = iota //2 n4 //3 ) const n5 = iota //0
Define orders of magnitude(Here<<
Indicates left-hand movement operation,1<<10
It means to shift the binary representation of 1 by 10 bits to the left, that is, by1
Become10000000000
, that is, 1024 in decimal. Similarly2<<2
It means to shift the binary representation of 2 to the left by 2 bits, that is,10
Become1000
, that is, 8 in decimal. )
const ( _ = iota KB = 1 << (10 * iota)// 1 left move 10 bits == 2^10 == 1024B = 1KB MB = 1 << (10 * iota)// On the original basis, move the left 10 bits, 2^20 == 1MB GB = 1 << (10 * iota) TB = 1 << (10 * iota) PB = 1 << (10 * iota) )
Multipleiota
Defined in one line
const ( a, b = iota + 1, iota + 2 //1,2 c, d //2,3 e, f //3,4 )
2. Basic data types
Integers in Golang
Integer types are divided into the following two categories:
Divided into:int8、int16、int32、int64
The corresponding unsigned integer:uint8、uint16、uint32、uint64
in,uint8
It's what we knowbyte
type,int16
Corresponding to C languageshort
type, int64 corresponds to C languagelong
type.
type | describe |
---|---|
uint8 | Unsigned 8-bit integer (0 to 255) |
uint16 | Unsigned 16-bit integer (0 to 65535) |
uint32 | Unsigned 32-bit integer (0 to 4294967295) |
uint64 | Unsigned 64-bit integer (0 to 18446744073709551615) |
int8 | Signed 8-bit integer (-128 to 127) |
int16 | Signed 16-bit integer (-32768 to 32767) |
int32 | Signed 32-bit integer (-2147483648 to 2147483647) |
int64 | Signed 64-bit integer (-9223372036854775808 to 9223372036854775807) |
Special type
type | describe |
---|---|
uint | It's uint32 on the 32-bit operating system, and it's uint64 on the 64-bit operating system. |
int | Int32 on the 32-bit operating system, int64 on the 64-bit operating system |
uintptr | Unsigned integer, used to store a pointer |
Notice: In useint
and uint
When typed, you cannot assume that it is a 32-bit or 64-bit integer, but consider the possible differences between int and uint on different platforms.
Things to noteGet built-in of the length of the objectlen()
The length returned by the function can be varied according to the byte length of different platforms. In actual use, the number of elements of slices or maps can be used.int
Let's express it. When it comes to binary transmission and reading and writing the structure description of files, in order to keep the file structure not affected by the byte lengths of different compile target platforms, do not useint
anduint
。
Digital representation
After Go1.13, the number literal syntax was introduced, so that developers can define numbers in binary, octal or hexadecimal floating point formats, such as:
v := 0b00101101
, represents 101101 in binary, equivalent to 45 in decimal.v := 0o377
, represents octal 377, equivalent to 255 in decimal.v := 0x1p-2
, represents 1 in hexadecimal divided by 2², which is 0.25.
And we are allowed to use_
To separate numbers, for example:v := 123_456
Indicates that the value of v is equal to 123456.
We can use the fmt function to display an integer in different binary form.
package main import "fmt" func main(){ // Decimal var a int = 10 ("%d \n", a) // 10 ("%b \n", a) // 1010 Placeholder %b means binary // Octal starts with 0 var b int = 077 ("%o \n", b) // 77 // Hexadecimal starts with 0x var c int = 0xff ("%x \n", c) // ff ("%X \n", c) // FF }
Floating point type in Golang
Go language supports two floating point numbers:float32
andfloat64
(default). These two floating point data formats followIEEE 754
standard: float32
The maximum range of floating point numbers is approximately 3.4e38
, you can use constant definitions:math.MaxFloat32
。 float64
The maximum range of floating point numbers is approximately1.8e308
, a constant definition can be used:math.MaxFloat64
。
When printing floating point numbers, you can usefmt
Package verb%f
, the code is as follows:
package main import ( "fmt" "math" ) func main() { ("%f\n", ) ("%.2f\n", ) }
Plural in Golang
complex64 and complex128
var c1 complex64 c1 = 1 + 2i var c2 complex128 c2 = 2 + 3i (c1) (c2)
The plural number has real and imaginary parts.The real and imaginary parts of complex64 are 32 bits, and the real and imaginary parts of complex128 are 64 bits.
Boolean value in Golang
In Go languagebool
The type declares Boolean data, Boolean data onlytrue (true)
andfalse (False)
Two values.
Notice:
Boolean type variableThe default value isfalse
。
In GoCasting to Boolean is not allowed.
Boolean typeIt cannot participate in numerical operations, nor can it be converted to other types.
Strings in Golang
Strings in Go appear as native data types, using strings is just like using other native data types (int, bool, float32, float64, etc.). Go languageInternal implementation of stringsUTF-8
coding. The value of the string isDouble quotes (")
The content in it can be directly added to the source code of Go language, such as:
s1 := "hello" s2 := "Hello"
String escape character
Common escape characters for strings in Go language include carriage return, line breaks, odd and double quotes, tab characters, etc., as shown in the following table.
Escape symbol | meaning |
---|---|
\r | Carriage return character (return to the beginning of the line) |
\n | Line breaks (jump directly to the same column position in the next row) |
\t | Tab symbols |
\' | Single quotes |
\" | Double quotes |
\\ | Backslash |
For example, we want to print a file path under a Windows platform:
package main import ( "fmt" ) func main() { ("str := \"c:\\Code\\hello_golang\\\"") }
Multi-line string
In Go language, you must use it when you define a multi-line string.Backquotes
character:
s1 := `First line Line 2 The third line ` (s1)
A line break between backticks will be used as a line break in the string, but all escape characters are invalid and the text will be output as it is.
Common operations of strings
method | introduce |
---|---|
len(str) | Find the length of the string |
+or | Stitching strings |
segmentation | |
Determine whether it contains | |
, | Prefix/suffix judgment |
(),() | Where the substring appears |
(a[]string, sep string) | Join operation |
byte and rune types in Golang
The element that makes up each string is called a "character", and characters can be obtained by traversing or single acquisition of string elements. Characters are wrapped in single quotes ('), such as:
var a := 'middle' var b := 'x'
There are two types of characters in Go:
-
uint8
Type, orbyte
Type, representingASCII
a character of the code. -
rune
Type, representing aUTF-8 characters
。
When you need to process Chinese, Japanese or other compound characters, you need to userune
type.rune
The type is actually aint32
。
Go uses a special rune type to handle Unicode, making Unicode-based text processing more convenient. You can also use the byte type for default string processing, taking into account performance and scalability.
// traverse stringsfunc traversalString() { s := "hello sand river" for i := 0; i < len(s); i++ { //byte ("%v(%c) ", s[i], s[i]) } () for _, r := range s { //rune ("%v(%c) ", r, r) } () }
Output:
104(h) 101(e) 108(l) 108(l) 111(o) 230(æ) 178(²) 153() 230(æ) 178(²) 179(³) 104(h) 101(e) 108(l) 108(l) 111(o) 27801(sand) 27827(river)
Because the next Chinese character encoding UTF8 consists of 3 to 4 bytes, we cannot simply traverse a string containing Chinese by bytes, otherwise the result of the first line in the output above will appear.
The underlying layer of a string is a byte array, so it can be used with []byte
Types convert each other. A string cannot be modified. A string is composed of bytes, so the length of the string is the length of the byte.Rune type is used to represent utf8 characters. A rune character consists of one or more bytes。
Modify string
To modify a string, you need to convert it to[]rune
or[]byte
, after completion, convert tostring
. Regardless of the conversion, memory is reassigned and the byte array is copied.
func changeString() { s1 := "big" //Crew type conversion byteS1 := []byte(s1) byteS1[0] = 'p' (string(byteS1)) s2 := "White Radish" runeS2 := []rune(s2) runeS2[0] = 'red' (string(runeS2)) }
Type conversion in Golang
There are only casts in Go language, no implicit types. This syntax can only be used when two types support conversion.
The basic syntax for cast type conversion is as follows:
T(expression)
Where T represents the type to be converted. Expressions include variables, complex operators, function return values, etc.
For example, when calculating the oblique length of a right triangle, use the Sqrt() function of the math package. This function receives parameters of float64 type, and the variables a and b are both of int type. At this time, you need to cast a and b to float64 type.
func sqrtDemo() { var a, b = 3, 4 var c int // () The received parameter is float64 type, and it needs to be cast c = int((float64(a*a + b*b))) (c) }
Practice questions
- Write code to define an integer, floating point, boolean, and string variables, using
()
Match%T
Print out the values and types of the above variables respectively. - Write code to count strings"
hello sand river little prince
"The number of Chinese characters in China.
3. if judgement and for loop
The most commonly used process controls in Go areif
andfor
,andswitch
andgoto
It is mainly a structure created to simplify code and reduce duplicate code, and belongs to the process control of the extended class.
if else(branch structure)
If basic writing method for conditional judgment
The format of if condition judgment in Go language is as follows:
if expression1 { Branches1 } else if expression2 { Branches2 } else{ Branches3 }
When the result of expression 1 istrue
When the expression 2 is satisfied, branch 1 is executed, otherwise, branch 2 is executed if it is satisfied. When none is satisfied, branch 3 is executed. ifelse if
andelse
They are all optional and can be selected according to actual needs.
Go language regulations andif
Matching left brackets{
Must be with ifand expressions
Put it in the same line,{
Putting it elsewhere will trigger a compilation error. Similarly, withelse
The matching { must also be withelse
Write on the same line,else
Must be with the previous oneif
orelse if
The braces on the right are on the same line.
For example:
func ifDemo1() { score := 65 if score >= 90 { ("A") } else if score > 75 { ("B") } else { ("C") } }
If conditional judgment special writing method
There is also a special way to write if condition judgment. You can add an execution statement before the if expression and then make judgments based on the variable value. For example:
func ifDemo2() { if score := 65; score >= 90 { ("A") } else if score > 75 { ("B") } else { ("C") } }
Thoughts: What is the difference between the two writing methods?
for(loop structure)
All loop types in the Go language can be done using the for keyword.
The basic format of the for loop is as follows:
for Initial statement;Conditional expression;Conclusion statement{ Loop body statement }
When the conditional expression returns true, the loop body keeps looping until the conditional expression returns false, automatically exits the loop.
func forDemo() { for i := 0; i < 10; i++ { (i) } }
The initial statement of the for loop can be ignored, but the semicolon after the initial statement must be written, for example:
func forDemo2() { i := 0 for ; i < 10; i++ { (i) } }
Both the initial statement and the end statement of the for loop can be omitted, for example:
func forDemo2() { i := 0 for ; i < 10; i++ { (i) } }
This writing method is similar to while in other programming languages. Add a conditional expression after while, and the loop continues when the conditional expression is satisfied, otherwise the loop ends.
Infinite loop
for { Loop body statement }
For loop can passbreak、goto、return、panic
The statement forces the loop to exit.
for range(key value loop)
Can be used in Gofor range
Iterates over arrays, slices, strings, maps and channels. passfor range
There are the following rules for the return value of the traversal:
Arrays, slices, strings return indexes and values. map returns keys and values. Channels only return values within the channel.
s := "Hello One Piece" for i,v := range d { ("%d %c\n",i,v); } // Output result0 h 1 e 2 l 3 l 4 o 5 7 ocean 8 thief 9 king
switch case
useswitch
Statements can easily make conditional judgments on a large number of values.
func switchDemo1() { finger := 3 switch finger { case 1: ("Thumbs up") case 2: ("index finger") case 3: ("Middle Finger") case 4: ("Ring Finger") case 5: ("Little Finger") default: ("Invalid input!") } }
Go language specifies eachswitch
There can only be onedefault
Branch.
A branch can have multiple values, and multiple case values are separated by English commas.
func testSwitch3() { switch n := 7; n { case 1, 3, 5, 7, 9: ("odd number") case 2, 4, 6, 8: ("even") default: (n) } }
The branch can also use expressions, and at this time, there is no need to judge variables after the switch statement. For example:
func switchDemo4() { age := 30 switch { case age < 25: ("Study hard") case age > 25 && age < 35: ("Work well") case age > 60: ("Enjoy it") default: ("It's great to be alive") } }
fallthrough
The syntax is OKExecute the next case that meets the condition
, is designed to be compatible with case in C language.
func switchDemo5() { s := "a" switch { case s == "a": ("a") fallthrough case s == "b": ("b") case s == "c": ("c") default: ("...") } }
Output:
a b
goto (jump to the specified tag)
goto
Statements are unconditional jumps between codes through tags.goto
Statements can be helpful in quickly jumping out of loops and avoiding repeated exits. Used in Gogoto
Statements can simplify the implementation process of some code. For example, when a double-layer nested for loop is about to exit:
func gotoDemo1() { var breakFlag bool for i := 0; i < 10; i++ { for j := 0; j < 10; j++ { if j == 2 { // Set the exit tag breakFlag = true break } ("%v-%v\n", i, j) } // Outer for loop judgment if breakFlag { break } } }
usegoto
Statements can simplify the code:
func gotoDemo2() { for i := 0; i < 10; i++ { for j := 0; j < 10; j++ { if j == 2 { // Set the exit tag goto breakTag } ("%v-%v\n", i, j) } } return // LabelbreakTag: ("End for loop") }
break(Breaking out of the loop)
break
The statement can endfor、switch
andselect
block of code.
break
The statement can also add a tag after the statement to indicate that the code block corresponding to a certain tag must be defined in the corresponding tag.for、switch
andselect
on the code block. For example:
func breakDemo1() { BREAKDEMO1: for i := 0; i < 10; i++ { for j := 0; j < 10; j++ { if j == 2 { break BREAKDEMO1 } ("%v-%v\n", i, j) } } ("...") }
Continue (continue the next loop)
continue
The statement can end the current loop and start the next loop iteration process, and is only used in the for loop.
existcontinue
When adding a tag after a statement, it means that the loop corresponding to the tag starts. For example:
func continueDemo() { forloop1: for i := 0; i < 5; i++ { // forloop2: for j := 0; j < 5; j++ { if i == 2 && j == 2 { continue forloop1 } ("%v-%v\n", i, j) } } }
Summarize
That’s all for this article. I hope it can help you and I hope you can pay more attention to more of my content!