当前位置:网站首页>Golang quick start (2)
Golang quick start (2)
2022-06-23 10:22:00 【Dog barking】
Catalog
Golang Array
An array is a collection of the same data type , Once the array length is defined, it cannot be modified , Arrays can be accessed by index
Its internal elements .
Define an array
var arr1 [3]int
var arr2 = [3]int{
1, 2, 3}
arr3 := [3]int{
1, 2, 3}
slice ( section )
The length of the array is fixed , Dynamic capacity expansion cannot be realized .
go A slice of language , Slice can be understood as , Variable length array , In fact, its bottom layer is to use the array implementation
Of , An automatic capacity expansion mechanism is added to the array . section (Slice) It's a variable length sequence of elements of the same type .
Declaring a slice is like declaring an array , If the length is not given, it will be slice
var arr1 []int
var arr2 = []int{
1, 2, 3}
arr3 := []int{
1, 2, 3}
Slice as reference type , have access to make establish
//make([] Type, size, capacity)
arr2 := make([]int, 10)
fmt.Printf("len(arr2): %v\n", len(arr2)) //10
Initialization slice
Direct initialization
var arr2 = []int{
1, 2, 3}
Initialize it with an array
var arr1 [3]int
var arr2 = arr1[:]
fmt.Printf("arr2: %T\n", arr2) //arr2: []int
You can also use part of an array to initialize it
var arr1 = [7]int{
1, 2, 3, 4, 5, 6, 7}
var arr2 = arr1[0:3]
fmt.Printf("arr2: %v\n", arr2) // arr2: [1 2 3]
sliced crud
add
Slice is a dynamic array , have access to append() Function to add elements to it
arr := []int{
1, 2, 3}
arr = append(arr, 4)
arr = append(arr, 5)
arr = append(arr, 6, 7, 8)
fmt.Printf("arr: %v\n", arr) //arr: [1 2 3 4 5 6 7 8]
delele
go There is no special way to delete slice elements in the language , You can use the properties of the slice itself to delete elements .
Delete subscript 2 The element of location
arr := []int{
0, 1, 2, 3, 4, 5, 6, 7, 8}
arr = append(arr[:2], arr[3:]...)
Delete index Element formula of position :arr = append(arr[:index], arr[index + 1:]…)
copy
Slicing is a reference type , By assignment , Will modify the original content ,go Provides copy() Function to copy the slice .
arr := []int{
0, 1, 2, 3, 4, 5, 6, 7, 18}
var arr2 = make([]int, 9)
copy(arr2, arr)
fmt.Printf("arr2: %v\n", arr2) // arr2: [0 1 2 3 4 5 6 7 18]
Map
initialization map
var mp1 map[string]string // Make a statement map, Memory has not been allocated Can't be used directly mp1 by nil var mp2 = map[string]string{
"1": "a"} // Initialize at the same time as the declaration
mp3 := make(map[string]string)
mp3["apple"] = " Apple "
// mp1["1"] = " One "
// mp1["2"] = " Two "
fmt.Printf("mp1: %v\n", mp1) //mp1: map[]
fmt.Printf("mp2: %v\n", mp2) //mp2: map[1:a]
fmt.Printf("mp3: %v\n", mp3) //mp3: map[apple: Apple ]
Traverse map
In general use for range Traverse
mp3 := make(map[string]string)
mp3["apple"] = " Apple "
mp3["pear"] = " pear "
mp3["banana"] = " Banana "
for _, value := range mp3 {
fmt.Printf("value: %v\n", value)
}
Delete map Elements
Use global delete function
mp1 := make(map[string]string, 10)
mp1["1"] = "1"
mp1["2"] = "2"
mp1["3"] = "3"
delete(mp1, "1")
fmt.Printf("mp1: %v\n", mp1) //mp1: map[2:2 3:3]
Golang function
go There is 3 Functions : Ordinary function 、 Anonymous functions ( Functions without names )、 Method ( It's defined in struct The function on ).
Be careful :
go A function with the same name is not allowed in a language , Function overload (overload).
go Functions in a language cannot be nested , But you can nest anonymous functions .
A function can be assigned directly to a variable as a value , Make this variable a function , It's kind of like C++ std::function.
Function arguments can have no name .
Define a function
func HelloWorld() {
fmt.Println("helloworld")
}
it is to be noted that , The first letter of a function needs to be capitalized to be called in other packages .
The return value of the function
Golang Multiple parameters are allowed to be returned
Functions can have 0 Or multiple return values , The return value needs to specify the data type , Return value passed return Keyword to specify .
return There can be parameters , There can be no parameters , These return values can have names , You can also have no name .go Functions in can have multiple return values .
func GetStringAndInt() (string, int) {
fmt.Println("GetStringAndInt")
return "haha", 10
}
func main() {
str, num := GetStringAndInt()
fmt.Printf("str: %v\n", str)
fmt.Printf("num: %v\n", num)
// GetStringAndInt
// str: haha
// num: 10
}
return When a parameter is specified in the keyword , The return value may not have a name . If return Omit parameters , Then the return value part must have a name
When the return value has a name , Must be enclosed in parentheses , Comma separated , Even if there is only one return value
But even if the return value is named ,return You can also force the name of other return values , in other words return Higher priority
The named return value is pre declared , Inside the function, you can use , There is no need to declare . The name of the named return value cannot be the same as the name of the function parameter , Otherwise, an error is reported and the variable is repeatedly defined
return There can be expressions in , But the assignment expression... Cannot appear , This may be different from other languages . for example return a+b That's right. , but return c = a + b It's wrong. .
Go One of the return values is often used as whether the function is executed successfully 、 Criteria for judging whether there is an error message . for example return ( value, exists)、return (value, ok)、 return (value, err)
When the return value of a function is too many , For example, there are 4 More than one return value , These return values should be collected into the container , Then return to the container . for example , Return values of the same type can be put into slice in , Different types of return values can be put into map in .
But when a function has multiple return values , If one or more of the return values do not want to be used , You can underline _ To discard these return values .
The parameters of the function
go The default language is value passing , Such as int、string、 Array It means that the copied copy is passed to the function , So function internal access 、 Modification does not affect the arguments .
go Languages can use variable length parameters , Sometimes the number of parameters cannot be determined , Variable length parameters can be used , You can define parameters in the function statement
Variable parameters
func Test2(str string, args ...int) {
fmt.Printf("str: %v\n", str)
for _, v := range args {
fmt.Printf("v: %v\n", v)
}
}
func main() {
Test2("hello", 1, 2, 3, 4)
}
Parameters passed by reference
map、slice、 interface 、channel These data types are themselves reference types , When passed as a function parameter , Modification inside the function also affects the arguments .
Function type
Use type Keyword defines a function type
func Func2(str string) (int, int) {
fmt.Printf("Func2: %v\n", str)
return 1, 2
}
func Func3(str string) (int, int) {
fmt.Printf("Func3: %v\n", str)
return 1, 2
}
type F1 func(string) (int, int)
func main() {
var f1 F1 = Func2
f1("hello")
f1 = Func3
f1("world")
}
Function passed as parameter
func Func1(str string) (int, int) {
fmt.Println("Func1")
fmt.Printf("str: %v\n", str)
return 11, 22
}
func Func2(f func(string) (int, int)) {
f("Func2 call")
fmt.Println("Func2")
}
func main() {
Func2(Func1)
}
Anonymous functions
Define an anonymous function
func main() {
f1 := func() {
fmt.Println(" Anonymous functions ")
}
f1()
}
Call directly
func main() {
func() {
fmt.Println(" Anonymous functions ")
}()
}
defer sentence
golang Of defer Statement will delay the statement that follows it . stay defer The belonging function is about to return when , Press the deferred statement to defer The definition is executed in reverse order , in other words , Be first defer The statement of is finally executed , Finally being defer The sentence of , First executed .
Generally used for resource release , Release fd, lock .
Example :
it is to be noted that , It is not executed in the out scope , Arrival function return Execution only
func main() {
{
defer fmt.Println("1")
defer fmt.Println("2")
defer fmt.Println("3")
defer fmt.Println("4")
}
fmt.Println("hehe")
// hehe
// 4
// 3
// 2
// 1
}
Pay attention to the following
fun_return Function takes precedence over fun_defer() The function executes first , It can be understood as defer Statement to } It will not be executed until it is completely finished
func fun_return() int {
fmt.Println("fun_return")
return 1
}
func fun_defer() {
fmt.Println("fun_defer")
}
func test() int {
defer fun_defer()
return fun_return()
}
func main() {
test()
// Print
//fun_return
// fun_defer
}
init function
init Function precedes main Function execution , Generally used for some initialization operations at the package level .
- init Function precedes main Function automatic execution , Cannot call manually
- init Function has no input parameters 、 Return value
- Each bag can have more than one init function
- Each source file of a package can also have multiple init function
- Of the same package init Execution order ,golang There is no clear definition , Be careful that the program does not rely on this order of execution .
- Different packages init The function determines the execution order according to the dependency of package import .
Example :
Cannot call manually
func init() {
fmt.Println("init1")
}
func init() {
fmt.Println("init2")
}
func main() {
fmt.Println("hello world")
// init1
// init2
// hello world
}
Golang The pointer
Golang The pointer to is missing C/C++ Pointers are powerful ,Golang The pointer cannot be offset and operated .
// Define a string Pointer to type
var pstr *string
// Define a int Pointer to type
var pint *int
fmt.Printf("pstr: %T\n", pstr) // pstr: *string
fmt.Printf("pint: %v\n", pint) // pint: *int
Golang Pointer array
Define an array of pointers
var parr [10]*int
fmt.Printf("parr: %T\n", parr) //parr: [10]*int
Assign a value to
arr := [10]int{
1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
var parr [10]*int
for i := 0; i < 10; i++ {
parr[i] = &arr[i]
}
for i := 0; i < 10; i++ {
fmt.Printf("parr[i]: %v\n", *parr[i])
}
Type definition and type alias
The type definition Type the alias
// The type definition
type MYINT1 int
// Type declaration
type MYINT2 = int
func main() {
// The type definition
var num1 MYINT1 = 1
fmt.Printf("num1: %T\n", num1) // num1: main.MYINT1
// Type declaration
var num2 MYINT2 = 1
fmt.Printf("num2: %T\n", num2) //num2: int
}
Type definitions are different from type aliases
Type mismatch , Compiler error
// The type definition
type MYINT1 int
func Func1(v MYINT1) {
fmt.Printf("v: %v\n", v)
}
func main() {
// The type definition
var num1 MYINT1 = 1
// Define a int Type variable
var num3 int = 1
Func1(num1)
Func1(num3) // Compiler error
}
Compile and pass ,MYINT2 The compiled type is actually int,MYINT2 It's just int Another name for
// Type declaration
type MYINT2 = int
func Func2(v MYINT2) {
fmt.Printf("v: %v\n", v)
}
func main() {
// Type declaration
var num2 MYINT2 = 1
// Define a int Type variable
var num3 int = 1
Func2(num2)
Func2(num3) // Compiler error
}
Type definition is equivalent to defining a new type , Different from the previous type . But the type alias does not define a new type , Instead, use an alias to replace the previous type. The type alias will only exist in the code , After compilation, the alias will not exist because the type alias is consistent with the original type , So the methods owned by the original type , You can also call... In the type alias , But if it's a redefined type , Then you can't call any of the previous methods
边栏推荐
- On shore experience of Chang'an University majoring in transportation in 2023
- 线程池在项目中使用的心得体会
- Fill the pit for repvgg? In fact, it is the repoptimizer open source of repvgg2
- Multithreaded exercises
- 2021-04-16 array
- Personal blog system graduation project opening report
- Mysql-03.工作中对SQL优化的心得体会
- Alimentation des animaux de compagnie basée sur stm32
- R和RStudio下载安装详细步骤
- Dr. Sun Jian was commemorated at the CVPR conference. The best student thesis was awarded to Tongji Ali. Lifeifei won the huangxutao Memorial Award
猜你喜欢
随机推荐
文件IO(1)
Year end answer sheet! Tencent cloud intelligent comprehensive strength ranks first in China!
Numerical calculation method
thymeleaf如何取url中请求参数值?
2021-05-11static关键字
Multithreaded exercises
Shengshihaotong enables high-quality development with industrial Digitalization
谷贱伤农,薪贱伤码农!
一个优秀速开发框架是什么样的?
thymeleaf中如何给onclick事件传值的方法
利用华为云ECS服务器搭建安防视频监控平台
Centre de calcul haute performance - nvme / nvme - of - nvme - of overview
Golang quick start (1)
Confessing with Snake games (with source code)
解决audio自动播放无效问题
Liujinhai, architect of zhongang Mining: lithium battery opens up a Xintiandi for fluorine chemical industry
2021-05-11 abstract class
2021-04-15
几款实用软件分享
春招面试经验汇总(技术岗)







