Can golang not use pointers?
#Sometimes when I look at other people's Go code, I find that some of them use pointers in the code, and some don't. (Recommended learning: go)
Suppose there is a structure type called Person, and it is found that some methods use func methodA (*person Person) as a parameter, or use func *( person Person) methodA() is used as the structure's own method, that is, the person structure can directly call methodA, but using a pointer.
Or you can see the usage of var personMap map[string]*Person in the map structure
If you transfer from java to golang, it may not be easy to understand. Because there are no pointers in the Java world, you can just pass it directly and use it. However, you need to pay attention to many things when going to golang.
So when should you use it? Why is it needed in some places?
If you don’t use pointers, you cannot assign values to the structure in some cases. Let’s look at a piece of code. This code does not use any pointers and first defines a bunch of objects for testing.
type Person struct { //person结构体,包含年龄,名称,车 age int name string car Car } type Car struct { //person名下的车 name string //车的名字 } var personMap map[string]Person //一个存放person的map func setName(person Person, name string) { //给参数person设置名字 person.name = name } func (person Person) setName(name string) { //设置名字 person.name = name } func printName(person Person){ //打印person的名字 fmt.Println(person.name) } func (person Person)printName(){ //结构体person自己支持打印名字 fmt.Println(person.name) }
Then write the main method. I will comment the printed results in the code. I can find that the assignment fails in many cases.
func main() { person := Person{} fmt.Println(person) //{0 {}} person.age = 12 person.name = "小明" person.car = Car{"宝马"} fmt.Println(person) //{12 小明 {宝马}},正常赋值给person变量,因为这是在方法里面的变量 setName(person, "小红") fmt.Println(person) //{12 小明 {宝马}},小红赋值失败,传递给setName方法的person没有赋值成功 person.setName("小红") fmt.Println(person) //{12 小明 {宝马}},person自己setName,还是失败 personMap = make(map[string]Person) personMap["test"] = person person = personMap["test"] person.name = "小红" fmt.Println(person) //{12 小红 {宝马}},从map中取出person,给小红赋值成功 for _, value := range personMap { //遍历map fmt.Println(value)//{12 小明 {宝马}},打印的还是小明,而不是小红,说明上面personMap["test"]对象赋值失败 } }
Next, change it to use a pointer
type Person struct { age int name string car Car } type Car struct { name string } var personMap map[string]*Person func setName(person *Person, name string) { person.name = name } func (person *Person) setName(name string) { person.name = name } func printName(person Person){ fmt.Println(person.name) } func (person Person)printName(){ fmt.Println(person.name) }
Modify the main method and use the & address character
func main() { person := Person{} fmt.Println(person) //{0 {}} person.age = 12 person.name = "小明" person.car = Car{"宝马"} fmt.Println(person) //打印{12 小明 {宝马}} setName(&person, "小红") fmt.Println(person) //{12 小红 {宝马}}, 成功赋值! person.setName("小黑") fmt.Println(person) //{12 小黑 {宝马}}, 成功赋值! personMap = make(map[string]*Person) personMap["test"] = &person person = *personMap["test"] person.name = "小兰" fmt.Println(person) //{12 小兰 {宝马}},成功赋值! for _, value := range personMap { fmt.Println(value) //&{12 小兰 {宝马}},读取的也是正确的小兰 } }
So we have To conclude, when we need to modify the variable content of the structure, the structure variable parameters passed in by the method need to use pointers , that is, when the address of the structure needs to modify the variables of the architecture in the map , you also need to use the structure address as the value of the map
If you just read the structure variable, you can pass the reference directly without using the pointer
*type The type variable here stores an address. This needs to be clear. You need to use &type to get the address.
The above is the detailed content of Can golang not use pointers?. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



Reading and writing files safely in Go is crucial. Guidelines include: Checking file permissions Closing files using defer Validating file paths Using context timeouts Following these guidelines ensures the security of your data and the robustness of your application.

How to configure connection pooling for Go database connections? Use the DB type in the database/sql package to create a database connection; set MaxOpenConns to control the maximum number of concurrent connections; set MaxIdleConns to set the maximum number of idle connections; set ConnMaxLifetime to control the maximum life cycle of the connection.

The Go framework stands out due to its high performance and concurrency advantages, but it also has some disadvantages, such as being relatively new, having a small developer ecosystem, and lacking some features. Additionally, rapid changes and learning curves can vary from framework to framework. The Gin framework is a popular choice for building RESTful APIs due to its efficient routing, built-in JSON support, and powerful error handling.

The difference between the GoLang framework and the Go framework is reflected in the internal architecture and external features. The GoLang framework is based on the Go standard library and extends its functionality, while the Go framework consists of independent libraries to achieve specific purposes. The GoLang framework is more flexible and the Go framework is easier to use. The GoLang framework has a slight advantage in performance, and the Go framework is more scalable. Case: gin-gonic (Go framework) is used to build REST API, while Echo (GoLang framework) is used to build web applications.

JSON data can be saved into a MySQL database by using the gjson library or the json.Unmarshal function. The gjson library provides convenience methods to parse JSON fields, and the json.Unmarshal function requires a target type pointer to unmarshal JSON data. Both methods require preparing SQL statements and performing insert operations to persist the data into the database.

Best practices: Create custom errors using well-defined error types (errors package) Provide more details Log errors appropriately Propagate errors correctly and avoid hiding or suppressing Wrap errors as needed to add context

The FindStringSubmatch function finds the first substring matched by a regular expression: the function returns a slice containing the matching substring, with the first element being the entire matched string and subsequent elements being individual substrings. Code example: regexp.FindStringSubmatch(text,pattern) returns a slice of matching substrings. Practical case: It can be used to match the domain name in the email address, for example: email:="user@example.com", pattern:=@([^\s]+)$ to get the domain name match[1].

Backend learning path: The exploration journey from front-end to back-end As a back-end beginner who transforms from front-end development, you already have the foundation of nodejs,...
