当前位置:网站首页>The way to learn go (II) basic types, variables and constants
The way to learn go (II) basic types, variables and constants
2022-07-06 07:18:00 【Tiger up】
1.go help Order and interpretation
go env For printing Go Environment information of language .
go run Command can compile and run the command source file .
go get You can download or update the specified code package and its dependent package from the Internet according to the requirements and actual situation , And compile and install them .
go build The command is used to compile the source files or code packages we specified and their dependency packages .
go install Used to compile and install the specified code packages and their dependent packages .
go clean The command will delete some files and directories generated by executing other commands .
go doc The command can be printed on Go Documents on language program entities . We can view the document by using the identifier of the program entity as the parameter of the command .
go test The command is used for Go Language program for testing .
go list The function of the command is to list the information of the specified code package .
go fix Will put all of the specified code package Go The old version code in the language source code file is revised to the new version code .
go vet It's a test for Go A simple tool for static errors in language source code .
go tool pprof Command to interactively access the contents of the profile .
2.go Built in type
(1) Value type
bool
int(32 or 64), int8, int16, int32, int64
uint(32 or 64), uint8(byte), uint16, uint32, uint64
float32, float64
string
complex64, complex128
array – Fixed length array
(2) Reference type ( The pointer ):
slice – Sequence arrays ( The most commonly used )
map – mapping
chan – The Conduit
(3) Function type
append – Used to append elements to an array 、slice in , Return the modified array 、slice
close – It's mainly used to close channel
delete – from map Delete in key Corresponding value
panic – Stop regular goroutine (panic and recover: For error handling )
recover – Allow programs to define goroutine Of panic action
real – return complex The real part of (complex、real imag: Used to create and manipulate complex numbers )
imag – return complex The imaginary part of
make – Used to allocate memory , return Type In itself ( It can only be applied to slice, map, channel)
new – Used to allocate memory , Mainly used to assign value types , such as int、struct. Return to point Type The pointer to
cap – capacity It means capacity , Used to return the maximum capacity of a type ( Can only be used for slicing and map)
copy – For copying and connecting slice, Returns the number of copies
len – To find the length , such as string、array、slice、map、channel , Return length
print、println – Underlying print function , In the deployment environment, it is recommended to use fmt package
(4) Interface error
type error interface {
// As long as it's done Error() function , The return value is String All have been realized err Interface
Error() String
}
3.init() And main()
The same thing :
Two functions cannot have any parameters and return values when they are defined , And Go Program calls automatically
Difference :
init Can be applied to any package , And multiple... Can be defined repeatedly
main Function can only be used for main In bag , And you can only define one
The execution order of the two functions :To the same go Of documents init() The call order is from top to bottom .
To the same package Different files in are compared by file name string “ From small to large ” Call... In each file in sequence init() function .
For different package, If not interdependent , according to main In bag ” First import Post call ” Call... In its package in the order of init(), If package There is dependence , First call the earliest dependent package Medium init(), Last call main function .
If init Used in function println() perhaps print() You will find that these two will not be executed in the order you think . These two functions are officially only recommended for use in the test environment , Don't use... For formal environments .
4. Operator
= Simple assignment operators , Assign the value of an expression to an lvalue
+= Add and then assign a value
-= Subtract and then assign a value
*= Multiply and assign a value
/= Divide and assign a value
%= The value is assigned after the remainder
<<= Left shift assignment
<<= Right shift after assignment
&= Bitwise and post assignment
l= Assign value by bit or after
^= Assign a value after bitwise XOR
&& Logic AND Operator . If the operands on both sides are True, Then for True, Otherwise False.
ll Logic OR Operator . If the operands on both sides have one True, Then for True, Otherwise False.
! Logic NOT Operator . If the condition is True, Then for False, Otherwise True.
== Check that the two values are equal , If equal returns True Otherwise return to False.
!= Check that the two values are not equal , If not equal return True Otherwise return to False.
Check that the left value is greater than the right value , If it's a return True Otherwise return to False.
= Check if the value on the left is greater than or equal to , If it's a return True Otherwise return to False.
< Check that the left value is less than the right value , If it's a return True Otherwise return to False.
<= Check that the left value is less than or equal to the right value , If it's a return True Otherwise return to False.
+ Add up
- Subtracting the
* Multiply
/ be divided by
% Seeking remainder
5. Variables and constants
(1) variable declaration 、 Batch variable declaration 、 Initialization of a variable
var name string
var age int
var isOk boo
var (
a string
b int
c bool
d float32
)
var name string = "pprof.cn"
var sex int = 1
# The compiler will also automatically derive variable types based on types
var name, sex = "pprof.cn", 1
(2) Short variables declare
package main
import (
"fmt"
)
// Global variables m
var m = 100
func main() {
n := 10
m := 200 // Local variables are declared here m
fmt.Println(m, n)
}
(3) Anonymous variables
func foo() (int, string) {
return 10, "Q1mi"
}
func main() {
x, _ := foo()
_, y := foo()
fmt.Println("x=", x)
fmt.Println("y=", y)
}
Anonymous variables do not take up the namespace , Memory will not be allocated , So there is no duplicate declaration between anonymous variables .
(4) Constant
const pi = 3.1415
const e = 2.7182
const When multiple constants are declared at the same time , If the value is omitted, it means that it is the same as the value in the previous line . for example :
const (
n1 = 100
n2
n3
)
In the above example , Constant n1、n2、n3 The values are all 100.
(5)iota
iota yes go Constant counter of language , Can only be used in constant expressions .
iota stay const The keyword will be reset to 0.const Every new line of constant declaration in will cause iota Count once (iota Can be understood as const Line index in statement block ). Use iota Can simplify the definition of , Useful when defining enumerations .
for instance :
const (
n1 = iota //0
n2 //1
n3 //2
n4 //3
)
Several common iota Example :
Use _ Skip some values
const (
n1 = iota //0
n2 //1
_
n4 //3
)
iota Make a statement to jump in the middle
const (
n1 = iota //0
n2 = 100 //100
n3 = iota //2
n4 //3
)
const n5 = iota //0
Define the order of magnitude ( there << Indicates move left operation ,1<<10 It means that you will 1 The binary representation of is shifted to the left 10 position , That is, by 1 Turned into 10000000000, That's decimal 1024. Empathy 2<<2 It means that you will 2 The binary representation of is shifted to the left 2 position , That is, by 10 Turned into 1000, That's decimal 8.)
const (
_ = iota
KB = 1 << (10 * iota)
MB = 1 << (10 * iota)
GB = 1 << (10 * iota)
TB = 1 << (10 * iota)
PB = 1 << (10 * iota)
)
Multiple iota It's defined on one line
const (
a, b = iota + 1, iota + 2 //1,2
c, d //2,3
e, f //3,4
)
6. Basic types
(1) integer
Integers are divided into the following two categories :
Divided by length :int8、int16、int32、int64 The corresponding unsigned integer :uint8、uint16、uint32、uint64
(2) floating-point
Go The language supports two floating-point numbers :float32 and float64. These two floating-point data formats follow IEEE 754 standard : float32
The maximum range of floating-point numbers is about 3.4e38, You can use constants to define :math.MaxFloat32. float64 The maximum range of floating-point numbers is about
1.8e308, You can use a constant to define :math.MaxFloat64.
(3) The plural
complex64 and complex128
Complex numbers have real parts and imaginary parts ,complex64 The real part and the virtual part are 32 position ,complex128 The real part and the virtual part are 64 position .
(4) Boolean value
Go In language bool Type to declare Boolean data , Boolean data is just true( really ) and false( false ) Two values .
Be careful :
The default value for Boolean variables is false.
Go Casting integers to Booleans... Is not allowed in the language .
Boolean cannot participate in numeric operations , It can't be converted with other types .
(5) character string
Go Strings in languages appear as native data types , Using strings is like using other native data types (int、bool、float32、float64 etc. ) equally . Go
The internal implementation of string in language uses UTF-8 code . The value of the string is double quotation marks (“) The content in , Can be in Go The source code of the language directly adds non ASCII Code character , for example :
s1 := "hello"
s2 := " Hello "
(6) String escape character
escape meaning
\r A carriage return ( Back to the beginning of the line )
\n A newline ( Jump directly to the same column in the next row )
\t tabs
’ Single quotation marks
" Double quotes
\ The backslash
(7) Multiline string
Go When you want to define a multiline string in a language , You have to use the back quote character :
s1 := ` first line The second line The third line `
fmt.Println(s1)
A line break between the back quotes will be used as a line break in the string , But all escape characters are invalid , The text will be output as is .
(8) Introduction to common operation methods of string
len(str) Find the length
+ or fmt.Sprintf String concatenation
strings.Split Division
strings.Contains Judge whether it includes strings.HasPrefix,strings.HasSuffix Prefix / Suffix judgment
strings.Index(),strings.LastIndex() Where the substring appears
strings.Join(a[]string,sep string) join operation
(9)byte and rune type
The elements that make up each string are called “ character ”, You can get the character by traversing or getting a single string element . The characters are in single quotation marks (’) Wrap it up , Such as :
var a := ‘ in ’
var b := ‘x’
Go There are two kinds of characters in language :
uint8 type , Or call it byte type , On behalf of ASCII A character of a code .
rune type , Representing one UTF-8 character .
When you need to deal with Chinese 、 When Japanese or other compound characters , You need to use rune type .rune Type is actually a int32.
Go Used a special rune Type to deal with Unicode, Based on Unicode Text processing is more convenient , You can also use byte Type for default string handling , Performance and scalability are taken care of
// Traversal string
func traversalString() {
s := "pprof.cn Blog "
for i := 0; i < len(s); i++ {
//byte
fmt.Printf("%v(%c) ", s[i], s[i])
}
fmt.Println()
for _, r := range s {
//rune
fmt.Printf("%v(%c) ", r, r)
}
fmt.Println()
}
Output :
112(p) 112(p) 114(r) 111(o) 102(f) 46(.) 99(c) 110(n) 229(å) 141() 154() 229(å) 174() 162(¢)
112(p) 112(p) 114(r) 111(o) 102(f) 46(.) 99(c) 110(n) 21338( Bo ) 23458( customer )
边栏推荐
- CDN acceleration and cracking anti-theft chain function
- LeetCode Algorithm 2181. Merge nodes between zero
- 杰理之普通透传测试---做数传搭配 APP 通信【篇】
- leetcode841. Keys and rooms (medium)
- Uncaught typeerror: cannot red properties of undefined (reading 'beforeeach') solution
- Supervisor usage document
- Kubernetes cluster builds ZABBIX monitoring platform
- Bio model realizes multi person chat
- Introduction to the basics of network security
- Cookie技术&Session技术&ServletContext对象
猜你喜欢
Upgraded wechat tool applet source code for mobile phone detection - supports a variety of main traffic modes
变量的命名规则十二条
Crawling exercise: Notice of crawling Henan Agricultural University
Wechat official account infinite callback authorization system source code, launched in the whole network
Leetcode 78: subset
leetcode704. 二分查找(查找某个元素,简单,不同写法)
WPF之MVVM
【线上问题处理】因代码造成mysql表死锁的问题,如何杀掉对应的进程
作者已死?AI正用藝術征服人類
Week6 weekly report
随机推荐
What does UDP attack mean? UDP attack prevention measures
【线上问题处理】因代码造成mysql表死锁的问题,如何杀掉对应的进程
Wechat brain competition answer applet_ Support the flow main belt with the latest question bank file
变量的命名规则十二条
树莓派3B更新vim
OpenJudge NOI 2.1 1661:Bomb Game
学go之路(二)基本类型及变量、常量
word删除括号里内容
杰理之蓝牙设备想要发送数据给手机,需要手机先打开 notify 通道【篇】
leetcode35. 搜索插入位置(简单,找插入位置,不同写法)
杰理之如若需要大包发送,需要手机端修改 MTU【篇】
杰理之开发板上电开机,就可以手机打开 NRF 的 APP【篇】
[some special grammars about C]
杰理之需要修改 gatt 的 profile 定义【篇】
#systemverilog# 可综合模型的结构总结
Uncaught typeerror: cannot red properties of undefined (reading 'beforeeach') solution
数字IC设计笔试题汇总(一)
杰理之BLE【篇】
杰理之AD 系列 MIDI 功能说明【篇】
Solution to the problem of breakthrough in OWASP juice shop shooting range