Home Backend Development Golang Introduction to functions and methods in go language

Introduction to functions and methods in go language

Jan 06, 2020 pm 05:51 PM
go language function

Introduction to functions and methods in go language

If you encounter a function declaration without a function body, it means that the function is not implemented in Go.

package math
func Sin(x float64) float //implemented in assembly language
Copy after login

If a variable name is set for each return value of a function, it will be initialized with the corresponding zero value, and the operand will be omitted in the return statement of the function. This usage is called bare return.

The error handling in Go is customary to perform a series of initialization checks first, and process the code that handles the failure logic first, and then the actual logic of the function. This makes the code more concise and avoids too many errors. Hierarchy.

When defining a function, you can use the function type as a parameter or as a return type. Is it a bit like a delegate to achieve closure? There are also anonymous functions, which are similar to lambda expressions. The strings.Map function can be used for experimentation.

func squares() func() int {
    var x int
    return func() int {
        x++
        return x * x
    }
}
func main() {
    f := squares()
    fmt.Println(f()) // "1"
    fmt.Println(f()) // "4"
    fmt.Println(f()) // "9"
    fmt.Println(f()) // "16"
}
Copy after login

There are variable references in anonymous functions and squares. This is why function values ​​are reference types and function values ​​are not comparable. Go uses closure technology to implement function values, and Go programmers also call function values ​​closures.

Pay attention to the example program in the anonymous function section of the golang Bible.

The variable parameter function of the Go language is very easy to use. You can pass multiple parameters of the same type, or you can directly pass in a slice of this type (note that you must use the... mark when passing in the slice. I I think it is to distinguish the same slice parameters, after all, the two are still somewhat different). If you want to use different types of variable parameters, then use the universal interfac{}, and just parse the variable parameters in the function body like a slice. .

Until the function containing the defer statement is executed, the function after the defer will not be executed, regardless of whether the function containing the defer statement ends normally through return or ends abnormally due to panic. You can execute multiple defer statements in a function, and their execution order is opposite to the declaration order

var mu sync.Mutex
var m = make(map[string]int)
func lookup(key string) int {
    mu.Lock()
    defer mu.Unlock()
    return m[key]
}
Copy after login

When debugging complex programs, the defer mechanism is also often used to record when to enter and exit a function.

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)) 
    }
}
Copy after login

We only need to name the return value of double first, and then add a defer statement. We can output the parameters and return value every time double is called.

func double(x int) (result int) {
    defer func() { fmt.Printf("double(%d) = %d\n", x,result) }()
    return x + x
}
_ = double(4)
// Output:
// "double(4) = 8"
Copy after login

To facilitate problem diagnosis, 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.

gopl.io/ch5/defer2
func main() {
    defer printStack()
    f(3)
}
func printStack() {
    var buf [4096]byte
    n := runtime.Stack(buf[:], false)
    os.Stdout.Write(buf[:n])
}
Copy after login

It is a bit strange that field names and method names with the same name cannot be defined for a structure.

Function pointer: There are actually function pointers in go. Let’s use go language to implement the table-driven mode.

package main

import (
    "fmt"
)

func add(a int, b int) int {
    return a + b 
}

func sub(a int, b int) int {
    return a - b 
}

func main() {
    fm := make(map[int]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)
    }   
}
Copy after login

Return local variable pointer:

Unlike C language, GO functions can return local change pointers, and the compiler will use escape analysis to decide whether to Allocate memory on the heap.

You can disable function inlining through the -gcflags "-l -m" parameter when compiling. Function inlining will have some impact on memory allocation, but the details are unclear.

There is no so-called reference passing for function parameters, they are all passed by value. The only difference is whether a copy object or a pointer is passed. In C language, it is generally recommended to pass pointer parameters to avoid copying objects and 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 on the heap. The performance consumption will be added to the cost of heap memory allocation and garbage collection, and in Copying small objects on the stack is actually very fast, so if the object is not particularly large or the original object really needs to be modified, there is generally no need to pass pointer parameters. In concurrent programming, the use of immutable objects (read-only or copied) is also advocated, which can eliminate the trouble of data synchronization.

The following will allocate memory on the heap. When compiling, pass -gcflags "-m" to view the assembly code:

func test(p *int) {
    go func() {
        println(p)
    }() 
}

func main() {
    x := 100 
    p := &x
    test(p)
}
Copy after login

Use outgoing parameters, it is recommended to use the return value, you can also use two Level pointer:

func test(p **int) {
    x := 100
    *p = &x
}

func main() {
    var p *int
    test(&p)
    println(*p)
}
Copy after login

For more go language knowledge, please pay attention to the go language tutorial column on the PHP Chinese website.

The above is the detailed content of Introduction to functions and methods in go language. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What libraries are used for floating point number operations in Go? What libraries are used for floating point number operations in Go? Apr 02, 2025 pm 02:06 PM

The library used for floating-point number operation in Go language introduces how to ensure the accuracy is...

What is the problem with Queue thread in Go's crawler Colly? What is the problem with Queue thread in Go's crawler Colly? Apr 02, 2025 pm 02:09 PM

Queue threading problem in Go crawler Colly explores the problem of using the Colly crawler library in Go language, developers often encounter problems with threads and request queues. �...

In Go, why does printing strings with Println and string() functions have different effects? In Go, why does printing strings with Println and string() functions have different effects? Apr 02, 2025 pm 02:03 PM

The difference between string printing in Go language: The difference in the effect of using Println and string() functions is in Go...

How to solve the user_id type conversion problem when using Redis Stream to implement message queues in Go language? How to solve the user_id type conversion problem when using Redis Stream to implement message queues in Go language? Apr 02, 2025 pm 04:54 PM

The problem of using RedisStream to implement message queues in Go language is using Go language and Redis...

What is the difference between `var` and `type` keyword definition structure in Go language? What is the difference between `var` and `type` keyword definition structure in Go language? Apr 02, 2025 pm 12:57 PM

Two ways to define structures in Go language: the difference between var and type keywords. When defining structures, Go language often sees two different ways of writing: First...

Which libraries in Go are developed by large companies or provided by well-known open source projects? Which libraries in Go are developed by large companies or provided by well-known open source projects? Apr 02, 2025 pm 04:12 PM

Which libraries in Go are developed by large companies or well-known open source projects? When programming in Go, developers often encounter some common needs, ...

What should I do if the custom structure labels in GoLand are not displayed? What should I do if the custom structure labels in GoLand are not displayed? Apr 02, 2025 pm 05:09 PM

What should I do if the custom structure labels in GoLand are not displayed? When using GoLand for Go language development, many developers will encounter custom structure tags...

When using sql.Open, why does not report an error when DSN passes empty? When using sql.Open, why does not report an error when DSN passes empty? Apr 02, 2025 pm 12:54 PM

When using sql.Open, why doesn’t the DSN report an error? In Go language, sql.Open...

See all articles