"Blockchain + Era will undoubtedly be the next tuyere, but now the blockchain industry professionals are experiencing bottlenecks," brother Lian Education blockchain college Dean Yin Cheng said, "I hope that through the brother even education blockchain training College for the community to train and transport more high-quality blockchain technology talents."
Closures in the Go language also refer to variables outside the function. Closures are implemented to ensure that as long as closures are used,
Variables referenced by closures will always exist, for example: package main
Import "FMT"
Func Main () {
var J int = 5
A: = Func () (func ()) {//the Func () in parentheses indicates that the return value is a func () function
var i int = 10
return func () {//Returns an anonymous function here
Fmt. Printf ("I, J:%v,%v\n", I, J)
}
} ()//curly braces followed by a parameter list means that the anonymous function is called, and the execution of the variable a here is equal to a function.
A ()//Call function A
J *= 2//modify variables outside the function j
A ()//Call function A again
}
Operation Result:
I, J:10, 5
I, J:10, 10
In the above example, the closure function that the variable a points to refers to the local variables I and J, the value of I is isolated, cannot be modified outside the closure, change the value of J, and then call a again to find that the result is a modified value. In the closure function that the variable a points to, only the internal anonymous function can access the variable I and cannot be accessed by other means, thus guaranteeing the security of I.
2. Error handling
2.1 Error interface
The go language introduces a standard pattern for error handling, the errors interface, which is defined as follows:
Type Error Interface {
Error () string
}
The creation error is usually as follows:
var e error = errors. New ("...")//need to use errors package
For most functions, if you want to return an error, you can roughly define it as the following pattern, with the error as a variety of return
The last of the values, but this is not a mandatory requirement:
Func Foo (param int) (res int,err error) {
//....
}
The code at the time of invocation recommends handling error conditions as follows:
1
2
N, Err: = Foo (0)
If err! = Nil {
Error handling
} else {
Use return value n
}
2.2 Defer keywords
There is a good design in the go language, the deferred (defer) statement, where you can add multiple defer statements to a function. When the function executes to the last, these defer statements are executed in reverse order, and finally the function returns. Especially when you are doing some open resources operation, encountered errors need to return early, before returning you need to close the corresponding resources, otherwise it is easy to cause problems such as resource leakage.
Func ReadWrite () bool {
File. Open ("file")
Do some work
If Failurex {
File. Close ()
return False
}
If Failurey {
File. Close ()
return False
}
File. Close ()
return True
}
We see a lot of duplicated code on it, and the go defer effectively solves this problem. With it, not only is the amount of code reduced a lot, but the program becomes more elegant.
Func ReadWrite () bool {
File. Open ("file")
Defer file. Close ()//Ensure resources are closed properly
If Failurex {
return False
}
If Failurey {
return False
}
return True
}
If there are many calls to defer, then defer is in LIFO mode
1
2
For I: = 0; I < 5; i++ {
Defer FMT. Printf ("%d", i)//output Result: 4 3 2 1 0
}
Defer a bit like the try{}finall{in Java}
2.3 Panic and recover functions
The go language has 2 built-in functions panic () and recover () to report and capture program errors that occur at run time, unlike error, where panic and recover are generally used inside functions. Be careful not to misuse panic and recover, which can lead to performance problems and are generally only used when unknown input and unreliable requests. Go language error handling process: When a function occurs during execution of an exception or encounters panic (), the normal statement terminates immediately, then executes the defer statement, reports the exception information, and finally exits the goroutine. If the recover () function is used in defer, an error message is captured that causes the error message to terminate the report. The example below is from the network
Package Main
Import (
"Log"//log package
"StrConv"//Character conversion package
)
Capturing program exceptions caused by unknown input
Func catch (nums ... int) int {
Defer func () {
Recover () Captures exceptions that occur at run time, avoids exceptions when the program is directly over, and is typically used within the defer function
If r: = Recover (); R! = Nil {
Log. Println ("[E]", r)//prints the captured exception information through log without causing the program to hang
}
}()
return nums[1] * nums[2] * nums[3]//index out of range
}
Unsolicited panic, deprecated, may cause performance issues
Func toFloat64 (num string) (float64, error) {
Defer func () {
If r: = Recover (); R! = Nil {
Log. Println ("[W]", R)
}
}()
if num = = "" {
Panic ("param is null")//Active Throw Panic
}
Return StrConv. parsefloat (num, 10)
}
Func Main () {
catch (2, 8)
ToFloat64 ("")
}
Operation Result:
2016/03/26 20:16:03 [E] Runtime error:index out of range
2016/03/26 20:16:03 [W] param is null
Finally, add nil to the introduction:
Golang's nil, which is conceptually null, none, nil, and Null in other languages, refers to a value of 0 or null.
Nil is a pre-stated identifier, also a keyword in the usual sense. In Golang, nil can only assign values to pointers,
A variable of channel, Func, interface, map, or slice type. If this rule is not followed, panic is raised.
High-energy early warning, brother even education block chain live course August continues to hit the hot!
The original price of 1188 Yuan of 12 block chain advanced courses, now only need 1 Yuan!
Also can receive free "Go Language foundation actual combat project development" and "Go language Advanced Combat Project development" textbook Two!!
Limited time limit!! First come first served!!
Http://www.ydma.cn/open/course/24