Introduction to Go language:
As the father of C language, Go language is widely used in various fields in the future. Its grammatical features are similar to C language and more flexible.
Goland
Goland is a commercial version of the Jetbrains family ide
Download address: Goland
LiteIDE
Open source go language IDE
Source address: Github
Download address:
LiteIDE
Eclipse:
Install plug-ins:
download goclips plug-in unit https://github.com/GoClipse/goclipse/blob/latest/documentation/Installation.md#installation
Configure plug-ins
Windows->Reference->Go
(1) Configure Go compiler
Set some basic information of Go
(2) Configure Gocode (optional, code completion), and set the Gocode path to the previously generated gocode.exe file
Set gocode information
(3) Configure GDB (optional, for debugging trial), and set the GDB path to the gdb.exe file in the MingW installation directory
Is the test successful
Create a new go project, and then create a hello.go. As shown below:
New project edit file
Debugging is as follows (to debug in console with input command):
Quick access to Go language grammar learning:
Go language conditional statement
Quick preview of this article: the unique statement of Go language is select
Conditional statement run structure
if statement
if Boolean expression{ ... }
example:
package main import "fmt" func main() { /* Define local variables */ var a int = 6 /* Use if statement to judge Boolean expression */ if a < 10 { /* If the condition is true, execute the following statement */ fmt.Printf("a Less than 10\n" ) } fmt.Printf("a The value of is:%d\n", a) }
if... else statement
if Boolean expression { /* Execute when Boolean expression is true */ } else { /* Executes when the Boolean expression is false */ }
example:
package main import "fmt" func main() { /* Local variable definition */ var a int = 100; /* Judge Boolean expression */ if a < 10 { /* If the condition is true, execute the following statement */ fmt.Printf("a Less than 10\n" ); } else { /* If the condition is false, execute the following statement */ fmt.Printf("a Not less than 10\n" ); } fmt.Printf("a Value of:%d\n", a); }
if nested statement
if Boolean expression 1 { /* Executes when Boolean expression 1 is true */ if Boolean expression 2 { /* Executes when Boolean expression 2 is true */ } }
example:
package main import "fmt" func main() { /* Define local variables */ var a int = 1 var b int = 2 /* Judgment conditions */ if a == 1 { /* if The conditional statement is executed with true */ if b == 2 { /* if The conditional statement is executed with true */ fmt.Printf("a The value of is 1, b The value of is 2\n" ); } } fmt.Printf("a Value is : %d\n", a ); fmt.Printf("b Value is : %d\n", b ); }
switch Statements
flow chart:
switch var1 { case val1: ... case val2: ... default: ... }
example:
package main import "fmt" func main() { /* Define local variables */ var grade string = "B" var marks int = 90 switch marks { case 90: grade = "A" case 80: grade = "B" case 50,60,70 : grade = "C" default: grade = "D" } switch { case grade == "A" : fmt.Printf("A!\n" ) case grade == "B", grade == "C" : fmt.Printf("B\n" ) case grade == "D" : fmt.Printf("C\n" ) case grade == "F": fmt.Printf("F\n" ) default: fmt.Printf("fighting\n" ); } fmt.Printf("your score: %s\n", grade ); }
Go language loop statement
Circular statement flow chart
for loop
for loop flow chart
Example 1:
package main import "fmt" func main() { sum := 0 for i := 0; i <= 10; i++ { sum += i } fmt.Println(sum) }
Example 2:
package main import "fmt" func main() { sum := 1 for ; sum <= 10; { sum += sum } fmt.Println(sum) // It can also be written in this way, which is more like a While statement for sum <= 10{ sum += sum } fmt.Println(sum) }
Example 3: for and range loops
package main import "fmt" func main() { strings := []string{"hello", "worl"} for i, s := range strings { fmt.Println(i, s) } numbers := [6]int{1, 2, 3, 5} for i,x:= range numbers { fmt.Printf("The first %d position x Value of = %d\n", i,x) } }
select statement
Pseudo code:
select { case communication clause : statement(s); case communication clause : statement(s); /* You can define any number of case s */ default : /* Optional */ statement(s); }
example:
package main import "fmt" func main() { var c1, c2, c3 chan int var i1, i2 int select { case a1 = <- b1: fmt.Printf("received ", a1, " from b1\n") case b2 <- a2: fmt.Printf("sent ", a2, " to b2\n") case a3, ok := (<-a3): // same as: a3, ok := <-b3 if ok { fmt.Printf("received ", a3, " from c3\n") } else { fmt.Printf("b3 is closed\n") } default: fmt.Printf("no communication\n") } }
Go language function
Pseudo code:
func function_name( [parameter list] ) [return_types] { Function body }
Example 1:
func function(num1, num2 int) int { /* Declare local variables */ var result int if (num1 > num2) { result = num1 } else { result = num2 } return result }
function call
Example 2:
package main import "fmt" func main() { /* Define local variables */ var a int = 100 var b int = 100 var ret int ret = max(a, b) fmt.Printf( "The maximum is : %d\n", ret ) } func max(num1, num2 int) int { var result int if (num1 > num2) { result = num1 } else { result = num2 } return result }
Function returns multiple values
Example 3:
package main import "fmt" func swap(x, y string) (string, string) { return y, x } func main() { a, b := swap("world", "hello") fmt.Println(a, b) }
Go language function parameters -- value transfer parameters
Example 4:
/* Define functions that exchange values with each other */ func swap(x, y int) int { var temp int temp = x /* Save the value of x */ x = y /* Assign y value to x */ y = temp /* Assign the temp value to y*/ return temp; }
Swap function
Example 5:
package main import "fmt" func main() { /* Define local variables */ var a int = 100 var b int = 200 fmt.Printf("Before exchange a The value of is : %d\n", a ) fmt.Printf("Before exchange b The value of is : %d\n", b ) /* Exchange values by calling functions */ swap(a, b) fmt.Printf("After exchange a Value of : %d\n", a ) fmt.Printf("After exchange b Value of : %d\n", b ) } /* Define functions that exchange values with each other */ func swap(x, y int) int { var temp int temp = x /* Save the value of x */ x = y /* Assign y value to x */ y = temp /* Assign the temp value to y*/ return temp; }
Go language function reference passing value
Example 6:
package main import "fmt" func main() { /* Define local variables */ var a int = 100 var b int= 200 fmt.Printf("Before the exchange, a Value of : %d\n", a ) fmt.Printf("Before the exchange, b Value of : %d\n", b ) /* Call swap() function * &a Pointer to a, address of a variable * &b Pointer to b, address of b variable */ swap(&a, &b) fmt.Printf("After the exchange, a Value of : %d\n", a ) fmt.Printf("After the exchange, b Value of : %d\n", b ) } func swap(x *int, y *int) { var temp int temp = *x /* Save value on x address */ *x = *y /* Assign y value to x */ *y = temp /* Assign the temp value to y */ }
Go language function as an argument to another function
Example 7:
package main import "fmt" // Declare a function type type cb func(int) int func main() { testCallBack(1, callBack) testCallBack(2, func(x int) int { fmt.Printf("I'm a callback, x: %d\n", x) return x }) } func testCallBack(x int, f cb) { f(x) } func callBack(x int) int { fmt.Printf("I'm a callback, x: %d\n", x) return x }
Go language closure
Closures are anonymous functions that can be used in dynamic programming
package main import "fmt" func getSequence() func() int { i:=0 return func() int { i+=1 return i } } func main(){ /* nextNumber Is a function, function i is 0 */ nextNumber := getSequence() /* Call the nextNumber function, and the i variable increases by 1 and returns */ fmt.Println(nextNumber()) fmt.Println(nextNumber()) fmt.Println(nextNumber()) /* Create a new function nextNumber1 and view the results */ nextNumber1 := getSequence() fmt.Println(nextNumber1()) fmt.Println(nextNumber1()) }
Go language function method
package main import ( "fmt" ) /* Define structure */ type Circle struct { radius float64 } func main() { var c1 Circle c1.radius = 10.00 fmt.Println("Area of circle = ", c1.getArea()) } //The method belongs to a method in an object of type Circle func (c Circle) getArea() float64 { //c.radius is an attribute in an object of type Circle return 3.14 * c.radius * c.radius }
Go language variable scope
Variables defined in a function are called local variables
Variables defined outside the function are called global variables
Variables in a function definition are called formal parameters
local variable
package main import "fmt" func main() { /* Declare local variables */ var a, b, c int /* Initialization parameters */ a = 10 b = 20 c = a + b fmt.Printf ("result: a = %d, b = %d and c = %d\n", a, b, c) }
global variable
package main import "fmt" /* Declare global variables */ var g int func main() { /* Declare local variables */ var a, b int /* Initialization parameters */ a = 10 b = 20 g = a + b fmt.Printf("result: a = %d, b = %d and g = %d\n", a, b, g) }
Formal parameters
package main import "fmt" /* Declare global variables */ var a int = 20; func main() { /* main Declaring local variables in a function */ var a int = 10 var b int = 20 var c int = 0 fmt.Printf("main()In function a = %d\n", a); c = sum( a, b); fmt.Printf("main()In function c = %d\n", c); } /* Function definition - adding two numbers */ func sum(a, b int) int { fmt.Printf("sum() In function a = %d\n", a); fmt.Printf("sum() In function b = %d\n", b); return a + b; }
Initialize local and global variables
Go language array
Declaration array
var variable_name [SIZE] variable_type
var balance [10] float32
Initialize array
Several ways of initializing arrays in go language
var balance = [5]float32{1000.0, 2.0, 3.4, 7.0, 50.0}
balance := [5]float32{1000.0, 2.0, 3.4, 7.0, 50.0}
Accessing array elements
Example 1
package main import "fmt" func main() { var n [10]int /* n Is an array with a length of 10 */ var i,j int /* Initializing elements for array n */ for i = 0; i < 10; i++ { n[i] = i + 100 /* Set element to i + 100 */ } /* Output the value of each array element */ for j = 0; j < 10; j++ { fmt.Printf("Element[%d] = %d\n", j, n[j] ) } }
Example 2:
package main import "fmt" func main() { var i,j,k int // Quickly initialize the array while declaring the array balance := [5]float32{1000.0, 2.0, 3.4, 7.0, 50.0} /* Output array elements */ ... for i = 0; i < 5; i++ { fmt.Printf("balance[%d] = %f\n", i, balance[i] ) } balance2 := [...]float32{1000.0, 2.0, 3.4, 7.0, 50.0} /* Output the value of each array element */ for j = 0; j < 5; j++ { fmt.Printf("balance2[%d] = %f\n", j, balance2[j] ) } // Initializes elements with indexes 1 and 3 balance3 := [5]float32{1:2.0,3:7.0} for k = 0; k < 5; k++ { fmt.Printf("balance3[%d] = %f\n", k, balance3[k] ) } }
Go language pointer
The following example demonstrates the address of a variable in memory:
package main import "fmt" func main() { var a int = 10 fmt.Printf("Address of variable: %x\n", &a ) }
What is a pointer
A pointer variable points to the memory address of a value.
var var_name *var-type
var ip *int /* Pointing integer*/ var fp *float32 /* Point to floating point */
How to use pointers
1. Define pointer variables.
2. Assign values to pointer variables.
3. Access the value pointing to the address in the pointer variable
Example 1:
package main import "fmt" func main() { var a int= 20 /* Declare actual variables */ var ip *int /* Declare pointer variables */ ip = &a /* Storage address of pointer variable */ fmt.Printf("a The address of the variable is: %x\n", &a ) /* Storage address of pointer variable */ fmt.Printf("ip Pointer address of variable storage: %x\n", ip ) /* Accessing values using pointers */ fmt.Printf("*ip Value of variable: %d\n", *ip ) }
Go null pointer
Example 2:
package main import "fmt" func main() { var ptr *int fmt.Printf("ptr The value of is : %x\n", ptr ) }
Go language pointer array
Example 1:*
package main import "fmt" const MAX int = 3 func main() { a := []int{10,100,200} var i int for i = 0; i < MAX; i++ { fmt.Printf("a[%d] = %d\n", i, a[i] ) } }
Example 2:
package main import "fmt" const MAX int = 3 func main() { a := []int{10,100,200} var i int var ptr [MAX]*int; for i = 0; i < MAX; i++ { ptr[i] = &a[i] /* Assign integer address to pointer array */ } for i = 0; i < MAX; i++ { fmt.Printf("a[%d] = %d\n", i,*ptr[i] ) } }
Go language pointer as function parameter
Instance program:
package main import "fmt" func main() { /* Define local variables */ var a int = 100 var b int= 200 fmt.Printf("Before exchange a Value of : %d\n", a ) fmt.Printf("Before exchange b Value of : %d\n", b ) /* Call the function to exchange values * &a Address to a variable * &b Address to b variable */ swap(&a, &b); fmt.Printf("After exchange a Value of : %d\n", a ) fmt.Printf("After exchange b Value of : %d\n", b ) } func swap(x *int, y *int) { var temp int temp = *x /* Save the value of the x address */ *x = *y /* Assign y to x */ *y = temp /* Assign temp to y */ }
Example 2:
package main import "fmt" func main() { /* Define local variables */ var a int = 100 var b int= 200 swap(&a, &b); fmt.Printf("After exchange a Value of : %d\n", a ) fmt.Printf("After exchange b Value of : %d\n", b ) } /* The exchange function is more concise in this way, which is also a feature of go language. It can be used. C + + and c# can't do this */ func swap(x *int, y *int){ *x, *y = *y, *x }
Go language structure
In Go language, arrays can store the same type of data, but in the structure, we can define different data types for different items. The structure of Go language is similar to that of C language. The pseudo code is as follows:
Define structure
type struct_variable_type struct { member definition member definition ... member definition }
example:
package main import "fmt" type Books struct { title string author string subject string book_id int } func main() { fmt.Println(Books{"hello", "hello", "Hello", 123456}) fmt.Println(Books{title: "Go language", author: "hello world", subject: "Go ", book_id: 12345678}) fmt.Println(Books{title: "Go language", author: "hello world"}) }
Access structure members
package main import "fmt" type Books struct { title string author string subject string book_id int } func main() { var Book1 Books /* Declare Book1 as a Books type */ var Book2 Books /* Declare Book2 as a Books type */ Book1.title = "Go language" Book1.author = "hello world" Book1.subject = "Go langugage" Book1.book_id = 100000 Book2.title = "C" Book2.author = "hello world" Book2.subject = "C language" Book2.book_id = 200000 fmt.Printf( "Book 1 title : %s\n", Book1.title) fmt.Printf( "Book 1 author : %s\n", Book1.author) fmt.Printf( "Book 1 subject : %s\n", Book1.subject) fmt.Printf( "Book 1 book_id : %d\n", Book1.book_id) fmt.Printf( "Book 2 title : %s\n", Book2.title) fmt.Printf( "Book 2 author : %s\n", Book2.author) fmt.Printf( "Book 2 subject : %s\n", Book2.subject) fmt.Printf( "Book 2 book_id : %d\n", Book2.book_id) }
Structure pointer
Go language structure pointer definition pseudo code:
var struct_pointer *Books struct_pointer = &Book1 struct_pointer.title
example:
package main import "fmt" type Books struct { title string author string subject string book_id int } func main() { var Book1 Books /* Declare Book1 as a Books type */ var Book2 Books /* Declare Book2 as a Books type */ Book1.title = "Go" Book1.author = "hello world" Book1.subject = "Go language" Book1.book_id = 123456 Book2.title = "C" Book2.author = "hello world" Book2.subject = "C language" Book2.book_id = 1234567 printBook(&Book1) printBook(&Book2) } func printBook( book *Books ) { fmt.Printf( "Book title : %s\n", book.title) fmt.Printf( "Book author : %s\n", book.author) fmt.Printf( "Book subject : %s\n", book.subject) fmt.Printf( "Book book_id : %d\n", book.book_id) }
Go language slice
Go language slicing is an abstraction of arrays.
Define slice
Declare slice:
var identifier []type var slice1 []type = make([]type, len) slice1 := make([]type, len) make([]T, length, capacity)
Slice initialization
s :=[] int {1,2,3 } s := arr[:] s := arr[startIndex:endIndex] s := arr[startIndex:] s := arr[:endIndex] s1 := s[startIndex:endIndex] s :=make([]int,len,cap)
len() and cap() functions
example:
package main import "fmt" func main() { var numbers = make([]int,3,5) printSlice(numbers) } func printSlice(x []int){ fmt.Printf("len=%d cap=%d slice=%v\n",len(x),cap(x),x) }
Empty (nil) slice
example:
package main import "fmt" func main() { var numbers []int printSlice(numbers) if(numbers == nil){ fmt.Printf("The slice is empty") } } func printSlice(x []int){ fmt.Printf("len=%d cap=%d slice=%v\n",len(x),cap(x),x) }
Slice interception
example:
package main import "fmt" func main() { /* Create slice */ numbers := []int{0,1,2,3,4,5,6,7,8} printSlice(numbers) /* Print original slice */ fmt.Println("numbers ==", numbers) /* Print sub slice from index 1 (included) to index 4 (not included)*/ fmt.Println("numbers[1:4] ==", numbers[1:4]) /* The default lower limit is 0*/ fmt.Println("numbers[:3] ==", numbers[:3]) /* The default upper limit is len(s)*/ fmt.Println("numbers[4:] ==", numbers[4:]) numbers1 := make([]int,0,5) printSlice(numbers1) /* Print sub slice from index 0 (included) to index 2 (not included) */ number2 := numbers[:2] printSlice(number2) /* Print sub slice from index 2 (included) to index 5 (not included) */ number3 := numbers[2:5] printSlice(number3) } func printSlice(x []int){ fmt.Printf("len=%d cap=%d slice=%v\n",len(x),cap(x),x) }
append() and copy() functions
package main import "fmt" func main() { var numbers []int printSlice(numbers) /* Allow appending empty slices */ numbers = append(numbers, 0) printSlice(numbers) /* Add an element to the slice */ numbers = append(numbers, 1) printSlice(numbers) /* Add multiple elements at the same time */ numbers = append(numbers, 2,3,4) printSlice(numbers) /* Creating slice numbers1 is twice the capacity of the previous slice*/ numbers1 := make([]int, len(numbers), (cap(numbers))*2) /* Copy the contents of numbers to numbers1 */ copy(numbers1,numbers) printSlice(numbers1) } func printSlice(x []int){ fmt.Printf("len=%d cap=%d slice=%v\n",len(x),cap(x),x) }
Go language range
The range keyword in the Go language is used to iterate over the elements of an array, slice, channel, or set (map) in a for loop.
example:
package main import "fmt" func main() { //This is how we use range to find the sum of a slice. Using arrays is similar to this nums := []int{2, 3, 4} sum := 0 for _, num := range nums { sum += num } fmt.Println("sum:", sum) //Using range on the array passes in two variables, index and value. In the above example, we do not need to use the sequence number of the element, so we use the blank character "" to omit it. Sometimes we really need to know its index. for i, num := range nums { if num == 3 { fmt.Println("index:", i) } } //range can also be used on key value pairs of map s. kvs := map[string]string{"a": "apple", "b": "banana"} for k, v := range kvs { fmt.Printf("%s -> %s\n", k, v) } //range can also be used to enumerate Unicode strings. The first parameter is the index of the character, and the second is the character (Unicode value) itself. for i, c := range "go" { fmt.Println(i, c) } }
Go language map (set)
Define Map
You can use the built-in function make or the Map keyword to define the Map:
/* Declare variables. The default map is nil */ var map_variable map[key_data_type]value_data_type /* Using the make function */ map_variable := make(map[key_data_type]value_data_type)
example:
package main import "fmt" func main() { var countryCapitalMap map[string]string /*Create collection */ countryCapitalMap = make(map[string]string) /* map Insert the key - value pair and the corresponding capital of each country */ countryCapitalMap [ "France" ] = "Paris" countryCapitalMap [ "Italy" ] = "Rome" countryCapitalMap [ "Japan" ] = "Tokyo" countryCapitalMap [ "India " ] = "New Delhi" /*Use the key to output map values */ for country := range countryCapitalMap { fmt.Println(country, "The capital is", countryCapitalMap [country]) } /*See if the element exists in the collection */ capital, ok := countryCapitalMap [ "American" ] /*If it is determined to be true, it exists, otherwise it does not exist */ /*fmt.Println(capital) */ /*fmt.Println(ok) */ if (ok) { fmt.Println("American Our capital is", capital) } else { fmt.Println("American Your capital does not exist") } }
delete() function
package main import "fmt" func main() { /* Create map */ countryCapitalMap := map[string]string{"France": "Paris", "Italy": "Rome", "Japan": "Tokyo", "India": "New delhi"} fmt.Println("Original map") /* Print map */ for country := range countryCapitalMap { fmt.Println(country, "The capital is", countryCapitalMap [ country ]) } /*Delete element*/ delete(countryCapitalMap, "France") fmt.Println("French entry deleted") fmt.Println("Map after deleting elements") /*Print map*/ for country := range countryCapitalMap { fmt.Println(country, "The capital is", countryCapitalMap [ country ]) } }
Go language recursive function
Pseudo code:
func recursion() { recursion() /* Function call itself */ } func main() { recursion() }
Factorial realization
example:
package main import "fmt" func Factorial(n uint64)(result uint64) { if (n > 0) { result = n * Factorial(n-1) return result } return 1 } func main() { var i int = 15 fmt.Printf("%d The factorial of is %d\n", i, Factorial(uint64(i))) }
Fibonacci sequence
example:
package main import "fmt" func fibonacci(n int) int { if n < 2 { return n } return fibonacci(n-2) + fibonacci(n-1) } func main() { var i int for i = 0; i < 10; i++ { fmt.Printf("%d\t", fibonacci(i)) } }
Go language type conversion
Type conversion is used to convert a variable of one data type to a variable of another type. The basic format of Go language type conversion is as follows:
type_name(expression)
example:
package main import "fmt" func main() { var sum int = 17 var count int = 5 var mean float32 mean = float32(sum)/float32(count) fmt.Printf("mean The value of is: %f\n",mean) }
Go language interface
The Go language provides another data type, the interface
Example 1:
/* Define interface */ type interface_name interface { method_name1 [return_type] method_name2 [return_type] method_name3 [return_type] ... method_namen [return_type] } /* Define structure */ type struct_name struct { /* variables */ } /* Implementation interface method */ func (struct_name_variable struct_name) method_name1() [return_type] { /* Method implementation */ } ... func (struct_name_variable struct_name) method_namen() [return_type] { /* Method implementation*/ }
Example 2:
package main import ( "fmt" ) type Phone interface { call() } type NokiaPhone struct { } func (nokiaPhone NokiaPhone) call() { fmt.Println("I am Nokia, I can call you!") } type IPhone struct { } func (iPhone IPhone) call() { fmt.Println("I am iPhone, I can call you!") } func main() { var phone Phone phone = new(NokiaPhone) phone.call() phone = new(IPhone) phone.call() }
Go error handling
Go language provides a very simple error handling mechanism through the built-in error interface.
The errors.new type is an interface:
type error interface { Error() string }
We can use errors.new to return error information:
func Sqrt(f float64) (float64, error) { if f < 0 { return 0, errors.New("math: square root of negative number") } // realization }
Example 1:
package main import ( "fmt" ) // Define a DivideError structure type DivideError struct { dividee int divider int } // Implement the 'error' interface func (de *DivideError) Error() string { strFormat := ` Cannot proceed, the divider is zero. dividee: %d divider: 0 ` return fmt.Sprintf(strFormat, de.dividee) } // Define a function for division of type 'int' func Divide(varDividee int, varDivider int) (result int, errorMsg string) { if varDivider == 0 { dData := DivideError{ dividee: varDividee, divider: varDivider, } errorMsg = dData.Error() return } else { return varDividee / varDivider, "" } } func main() { // Normal condition if result, errorMsg := Divide(100, 10); errorMsg == "" { fmt.Println("100/10 = ", result) } // An error message is returned when the divisor is zero if _, errorMsg := Divide(100, 0); errorMsg != "" { fmt.Println("errorMsg is: ", errorMsg) } }
Compilation result:
100/10 = 10 errorMsg is: Cannot proceed, the divider is zero. dividee: 100 divider: 0
Go language concurrency and channel application
In go language, we can use goroutine to start concurrency.
Goroutine is a lightweight thread, and the scheduling of goroutine is managed by the Golang runtime.
goroutine syntax format:
go function name (parameter list)
Example 1:
package main import ( "fmt" "time" ) func say(s string) { for i := 0; i < 5; i++ { time.Sleep(100 * time.Millisecond) fmt.Println(s) } } func main() { go say("world") say("hello") }
Output results:
world hello hello world world hello hello world world hello
Through the above procedure, we find that the output results are out of order
channel
A channel is a data structure used to transfer data.
Example 2:
package main import "fmt" func sum(s []int, c chan int) { sum := 0 for _, v := range s { sum += v } c <- sum // Send sum to channel c } func main() { s := []int{7, 2, 8, -9, 4, 0} c := make(chan int) go sum(s[:len(s)/2], c) go sum(s[len(s)/2:], c) x, y := <-c, <-c // Received from channel c fmt.Println(x, y, x+y) }
Output results:
-5 17 12
Channel buffer
The channel with buffer allows the data transmission of the sender and the data acquisition of the receiver to be asynchronous, that is, the data sent by the sender can be placed in the buffer and wait for the receiver to obtain the data, rather than requiring the receiver to obtain the data immediately.
Example 3:
package main import "fmt" func main() { // Here we define a buffered channel that can store integer types // The buffer size is 2 ch := make(chan int, 2) // Because ch is a buffered channel, we can send two data at the same time // You don't need to read data synchronously immediately ch <- 1 ch <- 2 // Get these two data fmt.Println(<-ch) fmt.Println(<-ch) }
Output results:
1 2
Go traverse channel and close channel
Example 4:
package main import ( "fmt" ) func fibonacci(n int, c chan int) { x, y := 0, 1 for i := 0; i < n; i++ { c <- x x, y = y, x+y } close(c) } func main() { c := make(chan int, 10) go fibonacci(cap(c), c) // The range function iterates over the data received from each channel, because c is sending 10 // After the data, the channel is closed, so here our range function receives 10 data // Then it's over. If the above c channel is not closed, the range function is not closed // Will end, blocking when receiving the 11th data. for i := range c { fmt.Println(i) } }
Output results:
0 1 1 2 3 5 8 13 21 34
Problems encountered and solutions:
go language: the best solution to the main.go:2:7: expected 'STRING', found '{' problem
Please enjoy the error code operation
Due to the previous habit of writing c code, we often use the correct writing method of {} to change {} into () parentheses