Home > Backend Development > Golang > How does a called function in Go access the parameters of the calling function?

How does a called function in Go access the parameters of the calling function?

PHPz
Release: 2024-02-09 21:15:09
forward
514 people have browsed it

Go 中调用的函数如何访问调用函数的参数?

The function called in Go can obtain the parameters of the calling function through the function parameters. In Go, parameters can be passed to functions by value or reference, and the function can obtain the value or pointer passed by the caller through the parameters. If the parameter is a value type, operations inside the function will be performed on the copy of the parameter and will not affect the original value passed by the caller. If the parameter is a pointer type, the operation inside the function will modify the original value pointed to by the pointer. In this way, functions can access and modify the parameters of the calling function, allowing for more flexible functionality. Whether it is a value type or pointer type parameter, the function can obtain the value or pointer passed by the caller through the parameter, and perform related operations inside the function.

Question content

Please refer to the reference code https://go.dev/play/p/yig2b6dkcoc (also pasted here):

Just like this code - the argument order is not passed to the sort.slice() function, but it is printed nicely in the call to the less() method of the sort package.

What are the attributes that implement this function?

package main

import (
    "fmt"
    "sort"
)

func main() {
    order := "abcd"
    s := "bca"
    fmt.Printf("ans: %v\n", customSortString(order, s))
}

func customSortString(order string, s string) string {
    sort.Slice([]byte(s), func(a, b int) bool {
        fmt.Printf("order: %v\n", order) // <------ How does this work? order is not passed to sort.Slice() function. 
        return s[a] < s[b]
    })
    return ""
}
Copy after login

Solution

https://www.php.cn/link/58b7483ba899e0ce4d97ac5eecf6fa99

Function literals are closures : they can reference variables defined in surrounding functions. These variables are then shared between surrounding functions and function literals, and they persist as long as they are accessible.

The above is the detailed content of How does a called function in Go access the parameters of the calling function?. For more information, please follow other related articles on the PHP Chinese website!

source:stackoverflow.com
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template