Table of Contents
Go pointer syntax and addressing problems in the use of viper library
Home Backend Development Golang Why is it necessary to pass pointers when using Go and viper libraries?

Why is it necessary to pass pointers when using Go and viper libraries?

Apr 02, 2025 pm 04:00 PM
go language ai Why igs

Go pointer syntax and addressing problems in the use of viper library

When programming in Go, it is crucial to understand the syntax and usage of pointers, especially when used in combination with third-party libraries such as Viper, you may encounter some issues that require deep understanding. The question we are going to discuss today is about how to correctly pass parameters in the use of the viper library and why passing a pointer to a pointer is necessary.

There are several modules in our project: setting, section, global and main. The specific code is as follows:

Setting module:

 type setting struct {
    vp *viper.viper
}

func newssetting() (*setting, error) {
    vp := viper.new()
    vp.setconfigname("config")
    vp.addconfigpath("configs/")
    vp.setconfigtype("yaml")
    err := vp.readinconfig()
    if err != nil {
        return nil, err
    }

    return &setting{vp: vp}, nil
}
Copy after login

Section module:

 type serversettings struct {
    runmode string
    httpport string
    readtimeout time.duration
    writetimeout time.duration
}

func (s *setting) readsection(k string, v interface{}) error {
    err := s.vp.unmarshalkey(k, v)
    if err != nil {
        return err
    }

    return nil
}
Copy after login

Global module:

 var serversetting *setting.serversettings
Copy after login

Main module:

 setting, err := setting.newsetting()

setting.readsection("server", &global.serversetting)
Copy after login

Now, if you modify the second line to setting.readsection("server", global.serversetting) in the main module, the error result must be addressable (a pointer). Why is this?

The problem is that global.serversetting is already a pointer, why do you need to pass its address when calling the readsection method?

There is a description in the source code of the viper library:

 // newdecoder returns a new decoder for the given configuration. once
// a decoder has been returned, the same configuration must not be used
// again.
func newdecoder(config *decoderconfig) (*decoder, error) {
    val := reflect.valueof(config.result)
    if val.kind() != reflect.ptr {
        return nil, errors.new("result must be a pointer")
    }

    val = val.elem()
    if !val.canaddr() {
        return nil, errors.new("result must be addressable (a pointer)")
    }
}
Copy after login

From this code, we can see that the passed parameters need not only be a pointer, but also need to be addressable (can be addressable). When you pass a pointer to a structure, it cannot be addressed by itself, thus causing an error.

To verify this, we can take a look at the following example:

 package main

import (
    "fmt"
    "reflect"
)

var a *db

type db struct {
}

func main() {
    val := reflect.valueof(a)
    val = val.elem()
    fmt.println(val.canaddr())

    val = reflect.valueof(&a)
    val = val.elem()
    fmt.println(val.canaddr())
}
Copy after login

Running this code will get the following output:

 false
true
Copy after login

This shows that when a is passed (i.e. a pointer), its elements cannot be addressed, while when &a is passed (i.e. a pointer of the pointer), its elements can be addressed.

Therefore, when using the readsection method, we need to pass &global.serversetting, because in this way, the address of a pointer is passed, which can be addressed, thus meeting the requirements of the viper library.

The above is the detailed content of Why is it necessary to pass pointers when using Go and viper libraries?. 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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months 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)

How Tomcat logs help troubleshoot memory leaks How Tomcat logs help troubleshoot memory leaks Apr 12, 2025 pm 11:42 PM

Tomcat logs are the key to diagnosing memory leak problems. By analyzing Tomcat logs, you can gain insight into memory usage and garbage collection (GC) behavior, effectively locate and resolve memory leaks. Here is how to troubleshoot memory leaks using Tomcat logs: 1. GC log analysis First, enable detailed GC logging. Add the following JVM options to the Tomcat startup parameters: -XX: PrintGCDetails-XX: PrintGCDateStamps-Xloggc:gc.log These parameters will generate a detailed GC log (gc.log), including information such as GC type, recycling object size and time. Analysis gc.log

How to implement file sorting by debian readdir How to implement file sorting by debian readdir Apr 13, 2025 am 09:06 AM

In Debian systems, the readdir function is used to read directory contents, but the order in which it returns is not predefined. To sort files in a directory, you need to read all files first, and then sort them using the qsort function. The following code demonstrates how to sort directory files using readdir and qsort in Debian system: #include#include#include#include#include//Custom comparison function, used for qsortintcompare(constvoid*a,constvoid*b){returnstrcmp(*(

How to optimize the performance of debian readdir How to optimize the performance of debian readdir Apr 13, 2025 am 08:48 AM

In Debian systems, readdir system calls are used to read directory contents. If its performance is not good, try the following optimization strategy: Simplify the number of directory files: Split large directories into multiple small directories as much as possible, reducing the number of items processed per readdir call. Enable directory content caching: build a cache mechanism, update the cache regularly or when directory content changes, and reduce frequent calls to readdir. Memory caches (such as Memcached or Redis) or local caches (such as files or databases) can be considered. Adopt efficient data structure: If you implement directory traversal by yourself, select more efficient data structures (such as hash tables instead of linear search) to store and access directory information

How to learn Debian syslog How to learn Debian syslog Apr 13, 2025 am 11:51 AM

This guide will guide you to learn how to use Syslog in Debian systems. Syslog is a key service in Linux systems for logging system and application log messages. It helps administrators monitor and analyze system activity to quickly identify and resolve problems. 1. Basic knowledge of Syslog The core functions of Syslog include: centrally collecting and managing log messages; supporting multiple log output formats and target locations (such as files or networks); providing real-time log viewing and filtering functions. 2. Install and configure Syslog (using Rsyslog) The Debian system uses Rsyslog by default. You can install it with the following command: sudoaptupdatesud

How to configure firewall rules for Debian syslog How to configure firewall rules for Debian syslog Apr 13, 2025 am 06:51 AM

This article describes how to configure firewall rules using iptables or ufw in Debian systems and use Syslog to record firewall activities. Method 1: Use iptablesiptables is a powerful command line firewall tool in Debian system. View existing rules: Use the following command to view the current iptables rules: sudoiptables-L-n-v allows specific IP access: For example, allow IP address 192.168.1.100 to access port 80: sudoiptables-AINPUT-ptcp--dport80-s192.16

How debian readdir integrates with other tools How debian readdir integrates with other tools Apr 13, 2025 am 09:42 AM

The readdir function in the Debian system is a system call used to read directory contents and is often used in C programming. This article will explain how to integrate readdir with other tools to enhance its functionality. Method 1: Combining C language program and pipeline First, write a C program to call the readdir function and output the result: #include#include#include#includeintmain(intargc,char*argv[]){DIR*dir;structdirent*entry;if(argc!=2){

Debian mail server SSL certificate installation method Debian mail server SSL certificate installation method Apr 13, 2025 am 11:39 AM

The steps to install an SSL certificate on the Debian mail server are as follows: 1. Install the OpenSSL toolkit First, make sure that the OpenSSL toolkit is already installed on your system. If not installed, you can use the following command to install: sudoapt-getupdatesudoapt-getinstallopenssl2. Generate private key and certificate request Next, use OpenSSL to generate a 2048-bit RSA private key and a certificate request (CSR): openss

Debian mail server firewall configuration tips Debian mail server firewall configuration tips Apr 13, 2025 am 11:42 AM

Configuring a Debian mail server's firewall is an important step in ensuring server security. The following are several commonly used firewall configuration methods, including the use of iptables and firewalld. Use iptables to configure firewall to install iptables (if not already installed): sudoapt-getupdatesudoapt-getinstalliptablesView current iptables rules: sudoiptables-L configuration

See all articles