In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-04-01 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
What are the functions and methods in the go language, many novices are not very clear about this, in order to help you solve this problem, the following editor will explain in detail for you, people with this need can come to learn, I hope you can get something.
If you encounter a function declaration that does not have a function body, it means that the function is not implemented in Go.
Package math
Func Sin (x float64) float / / implemented in assembly language
If you set a variable name for each return value of a function, it is initialized with the corresponding zero value and the operands are omitted in the function's return statement, which is called bare return.
In error handling in go, it is customary to first carry out a series of initialization checks to deal with the code that deals with the failed logic first, and then the actual logic of the function, which makes the code more concise and avoids excessive hierarchical structure.
Function definition, you can use the function type as a parameter, can also be used as a return type, is not a bit similar to the delegate, so as to achieve closure. There are also anonymous functions that are similar to lambda expressions. The strings.Map function can be tested.
Func squares () func () int {
Var x int
Return func () int {
Xerox +
Return x * x
}
}
Func main () {
F: = squares ()
Fmt.Println (f ()) / / "1"
Fmt.Println (f ()) / / "4"
Fmt.Println (f ()) / / "9"
Fmt.Println (f ()) / / "16"
}
In anonymous functions and squares, there are variable references. This is why the function value is a reference type and the function value is not comparable. Go uses closures technology to implement function values, and Go programmers also call function values closures.
Note the example program in the anonymous functions section of the golang Bible.
The variable parameter function of go language is very easy to use, you can pass multiple parameters of the same type, or you can pass in a slice of that type directly. Tag, I think it should be to distinguish it from the slice parameter, after all, the two are still a little different). If you want to use different types of variable parameters, then use the omnipotent interfac {}, and parse the variable parameter in the function body like parsing slices.
The function after the defer is not executed until the function containing the defer statement is executed, whether the function containing the defer statement ends normally through return or because of an exception caused by panic. You can execute multiple defer statements in a function in reverse order of declaration.
Var mu sync.Mutex
Var m = make (map [string] int)
Func lookup (key string) int {
Mu.Lock ()
Defer mu.Unlock ()
Return m [key]
}
When debugging complex programs, the defer mechanism is also often used to record when to enter and exit functions.
Func bigSlowOperation () {
Defer trace ("bigSlowOperation") () / don't forget the
Extra parentheses
/ /... lots of work...
Time.Sleep (10 * time.Second) / / simulate slow
Operation by sleeping
}
Func trace (msg string) func () {
Start: = time.Now ()
Log.Printf ("enter% s", msg)
Return func () {
Log.Printf ("exit s (s)", msg,time.Since (start))
}
}
We just need to name the return value of double first, then add the defer statement, and we can output parameters and return values each time double is called.
Func double (x int) (result int) {
Defer func () {fmt.Printf ("double (% d) =% d\ n", XMagne result)} ()
Return x + x
}
_ = double (4)
/ / Output:
/ / "double (4) = 8"
To make it easier to diagnose problems, the runtime package allows programmers to output stack information. In the following example, we output stack information by delaying the call to printStack in the main function.
Io/ch6/defer2
Func main () {
Defer printStack ()
F (3)
}
Func printStack () {
Var buf [4096] byte
N: = runtime.Stack (buf [:], false)
Os.Stdout.Write (buf [: n])
}
It's a bit strange that you can't define a field name and a method name with the same name for a structure.
Function pointers: there are also function pointers in go. The table-driven mode is implemented in go language below.
Package main
Import (
"fmt"
)
Func add (an int, b int) int {
Return a + b
}
Func sub (an int, b int) int {
Return a-b
}
Func main () {
Fm: = make (func (int, int) int)
Fm [1001] = add
Fm [1002] = sub
Protocol: = 2001
I: = 1
J: = 2
If func_handle, ok: = fm [protocol]; ok {
Println (func_handle (I, j))
} else {
Fmt.Printf ("protocol:% d not register!", protocol)
}
}
Returns the local variable pointer:
Unlike the C language, GO functions can return local change pointers, and the compiler uses escape analysis (escape analysis) to decide whether to allocate memory on the heap.
Function inlining can be disabled at compile time through the-gcflags "- l-m" parameter, which has some impact on memory allocation, but it is not clear.
Function parameters do not have the so-called reference passing, they are all passed by values, and the only difference is whether they pass a copy object or a pointer. In C language, it is generally recommended to pass pointer parameters to avoid copying objects to improve efficiency.
But in go, the copied pointer will extend the life cycle of the target object, and may also cause it to be allocated to the heap, then performance consumption will add the cost of heap memory allocation and garbage collection, while copying small objects on the stack is actually very fast, so if it is not a very large object or really needs to modify the original object, generally do not need to pass pointer parameters. In concurrent programming, the use of immutable objects (read-only or replication) is also promoted to eliminate the hassle of data synchronization.
Memory is allocated on the heap as follows, and the assembly code can be viewed with-gcflags "- m" at compile time:
Func test (p * int) {
Go func () {
Println (p)
} ()
}
Func main () {
X: = 100
P: = & x
Test (p)
}
Using outgoing parameters, it is recommended to use return values, or you can use secondary pointers:
Func test (p * * int) {
X: = 100
* p = & x
}
Func main () {
Var p * int
Test & p
Println (* p)
}
Is it helpful for you to read the above content? If you want to know more about the relevant knowledge or read more related articles, please follow the industry information channel, thank you for your support.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.