Home Backend Development Golang Go function parameter passing: Why does pointer variable remain unchanged after being modified inside the function?

Go function parameter passing: Why does pointer variable remain unchanged after being modified inside the function?

Apr 02, 2025 am 09:21 AM
mysql go language ai Why

Go function parameter passing: Why does pointer variable remain unchanged after being modified inside the function?

Pointer variable trap in Go function parameter passing: Why is it invalid to modify external variables in the function?

This article analyzes common problems about pointer variable assignment in a Go language program. The program tries to modify the pointer variable to the database connection object inside the function, but the variable in the main function has not been modified.

The following code snippet shows this problem:

 var db *sql.DB

func main() {
    initDB(db)
    fmt.Println(db) // Print<nil>
}

func initDB(db *sql.DB) {
    var err error
    db, err = sql.Open("mysql", "root:123456@tcp(127.0.0.1:3306)/data")
    checkErr(err)
    db.SetMaxOpenConns(100)
    db.SetMaxIdleConns(100)
    db.SetConnMaxLifetime(time.Minute * 3)
    if err := db.Ping(); err != nil {
        checkErr(err)
    }
    fmt.Println(db) // What is printed here is the correct value}

func checkErr(err error) {
    if err != nil {
        panic(err)
    }
}</nil>
Copy after login

db printed by main function is still nil , and the initDB function has successfully connected to the database. This is because the function parameter passing mechanism of Go language is value passing. Even if the parameter is a pointer type, the passed copy of the pointer value.

In the initDB function, db, err := sql.Open(...) creates a new *sql.DB object and assigns the object to the local variable db inside initDB function. This does not modify the pointing of the db variable in the main function. After the initDB function ends, its local variable db is destroyed, and db in the main function is still nil .

To correctly modify the db variable in the main function, you need to use a pointer to a pointer, or use a pointer receiver in the initDB function. Here is how to use pointers to solve this problem:

 var db *sql.DB

func main() {
    initDB(&db)
    fmt.Println(db) // The correct value will be printed now}

func initDB(db **sql.DB) {
    var err error
    *db, err = sql.Open("mysql", "root:123456@tcp(127.0.0.1:3306)/data")
    checkErr(err)
    (*db).SetMaxOpenConns(100)
    (*db).SetMaxIdleConns(100)
    (*db).SetConnMaxLifetime(time.Minute * 3)
    if err := (*db).Ping(); err != nil {
        checkErr(err)
    }
    fmt.Println(*db) // What is printed here is the correct value}

func checkErr(err error) {
    if err != nil {
        panic(err)
    }
}
Copy after login

By passing the address of db ( &db ), the initDB function can directly modify the pointing of the db variable in the main function.

The above is the detailed content of Go function parameter passing: Why does pointer variable remain unchanged after being modified inside the function?. 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 Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

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)

Hot Topics

Java Tutorial
1667
14
PHP Tutorial
1273
29
C# Tutorial
1255
24
The TOP5 of the safest exchanges in 2025: Black U's guide to avoid pits, the rule of 100% of funds to save lives The TOP5 of the safest exchanges in 2025: Black U's guide to avoid pits, the rule of 100% of funds to save lives May 08, 2025 pm 08:27 PM

In the field of cryptocurrency trading, the security of exchanges has always been the focus of users. In 2025, after years of development and evolution, some exchanges stand out with their outstanding security measures and user experience. This article will introduce the five most secure exchanges in 2025 and provide practical guides on how to avoid Black U (hacker attacks users) to ensure your funds are 100% secure.

MySQL: A Practical Application of SQL MySQL: A Practical Application of SQL May 08, 2025 am 12:12 AM

MySQL is popular because of its excellent performance and ease of use and maintenance. 1. Create database and tables: Use the CREATEDATABASE and CREATETABLE commands. 2. Insert and query data: operate data through INSERTINTO and SELECT statements. 3. Optimize query: Use indexes and EXPLAIN statements to improve performance.

AI and Composer: Enhancing Code Quality and Development AI and Composer: Enhancing Code Quality and Development May 09, 2025 am 12:20 AM

In Composer, AI mainly improves development efficiency and code quality through dependency recommendation, dependency conflict resolution and code quality improvement. 1. AI can recommend appropriate dependency packages according to project needs. 2. AI provides intelligent solutions to deal with dependency conflicts. 3. AI reviews code and provides optimization suggestions to improve code quality. Through these functions, developers can focus more on the implementation of business logic.

Top 10 digital virtual currency trading apps in 2025 Summary of the top 10 digital currency exchange apps Top 10 digital virtual currency trading apps in 2025 Summary of the top 10 digital currency exchange apps May 08, 2025 pm 05:24 PM

Ranking of the top ten digital virtual currency trading apps in 2025: 1. Binance: Leading the world, providing efficient transactions and a variety of financial products. 2. OKX: It is innovative and diverse, supporting a variety of transaction types. 3. Huobi: Stable and reliable, with high-quality service. 4. Coinbase: Be friendly for beginners and simple interface. 5. Kraken: The first choice for professional traders, with powerful tools. 6. Bitfinex: efficient trading, rich trading pairs. 7. Bittrex: Safety compliance, regulatory cooperation.

The latest download tutorial for Ouyi OKX6.118.0 version The latest download tutorial for Ouyi OKX6.118.0 version May 07, 2025 pm 06:51 PM

The latest download tutorial for Ouyi OKX6.118.0 version: 1. Click on the quick link in the article; 2. Click on the download (if you are a web user, please register the information first). The latest Android version v6.118.0 optimizes some functions and experiences to make trading easier. Update the app now to experience a more extreme trading experience.

Top 10 cryptocurrency platforms in the world that support multi-chain transactions are authoritatively released in 2025 Top 10 cryptocurrency platforms in the world that support multi-chain transactions are authoritatively released in 2025 May 08, 2025 pm 07:15 PM

According to the latest evaluations and industry trends from authoritative institutions in 2025, the following are the top ten cryptocurrency platforms in the world that support multi-chain transactions, combining transaction volume, technological innovation, compliance and user reputation comprehensive analysis:

Strategy for making money with zero foundation: 5 types of altcoins that must be stocked in 2025, make sure to make 50 times more profitable! Strategy for making money with zero foundation: 5 types of altcoins that must be stocked in 2025, make sure to make 50 times more profitable! May 08, 2025 pm 08:30 PM

In cryptocurrency markets, altcoins are often seen by investors as potentially high-return assets. Although there are many altcoins on the market, not all altcoins can bring the expected benefits. This article will provide a detailed guide for investors with zero foundation, introducing the 5 altcoins worth hoarding in 2025, and explaining how to achieve the goal of making a 50x steady profit through these investments.

Ouyi okx exchange v6.118.0 official IOS version download address Ouyi okx exchange v6.118.0 official IOS version download address May 07, 2025 pm 06:09 PM

The latest download address of Ouyi OKX6.118.0 version: 1. Click on the shortcut link in the article; 2. Click on the download (if you are a web user, please register the information first). The latest Android version v6.118.0 optimizes some functions and experiences to make trading easier. Update the app now to experience a more extreme trading experience.

See all articles