How to pass indefinite parameters in golang
Golang's variable parameters
The variable parameter is a placeholder. You can assign one or more parameters to this placeholder, so no matter The actual number of parameters can be handled by variable parameters. Let's take a look at the declaration of variable parameters:
func Printf(format string, a ...interface{}) (n int, err error) func Println(a ...interface{}) (n int, err error)
Variable parameters use name...Type The formal declaration is in the parameter list of the function, and it needs to be the last parameter in the parameter list. This is similar to other languages;
The variable parameters will be converted to the corresponding []Type type in the function, so we You can get the parameters passed to the function just like when using slice;
One thing worth noting is that golang's variable parameters do not need to force the occurrence of bound parameters.
For example, I want to implement a function sum that sums any integers in C language:
int sum(int num, ...) { // todo }
We can only use it if we specify at least one fixed formal parameter (num) first. ..Variable parameters do not need to be done in golang:
func sum(nums ...int) int { //todo }
This is also one of the embodiments of the concise syntax of golang.
Passing parameters to... variable parameters
There are two forms of passing parameters to functions with variable parameters. The first one is no different from the usual parameter passing. Take An example of sum in this section is:
sum(1, 2, 3) sum(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
It is the same as an ordinary function call except that the number of parameters changes dynamically.
The second form is to use the... operator to pass parameters in the form of a variable..., the variable here must be a slice of the same type as the variable parameter, and cannot be other types (yes ,
Arrays are not allowed either), look at an example:
numbers := []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10} sum(numbers...) // 和sum(1, 2, 3, 4, 5, 6, 7, 8, 9. 10)等价
The most commonly used place for this form is in the built-in function append:
result := []int{1, 3} data := []int{5, 7, 9} result = append(result, data...) // result == []int{1, 3, 5, 7, 9}
Is it related to python? The unpacking operation is very similar, yes, in most cases you can treat the... operator as golang's unpacking operation, but there are a few differences that you should pay attention to:
First, you can only use the... operator for the slice type:
arr := [...]int{1, 2, 3, 4, 5} sum(arr...) // 编译无法通过
You will see an error message like this:
cannot use arr (type [5]int) as type []int in argument to sum
This is because the variable parameter is actually a slice,... The operator is syntactic sugar. It copies the previous slice directly to the variable parameter, instead of unpacking it into independent n parameters and then passing them
. This is why I only say... The reason why the .operator looks like unpack.
The second thing to note is that you cannot mix independent parameter passing and... operators. Let’s look at another example:
slice := []int{2, 3, 4, 5} sum(1, slice...) // 无法通过编译
This time you will see a relatively long error message:
too many arguments in call to sum have (number, []int...) want (...int)
This is for the same reason as mentioned before. The... operator directly replaces the variable parameters with slice, which causes the previous independently given parameter to no longer be counted as variable parameters. Within the scope
, the parameter list of the function changes from (...int) to (int, ...int), which ultimately causes the function type mismatch and compilation failure.
The correct approach is also very simple. Do not mix and use... operators to pass parameters to variable parameters.
After reading this article and making some simple connections, I believe you will be able to master the use of golang variable parameters.
The above is the detailed content of How to pass indefinite parameters in golang. 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



OpenSSL, as an open source library widely used in secure communications, provides encryption algorithms, keys and certificate management functions. However, there are some known security vulnerabilities in its historical version, some of which are extremely harmful. This article will focus on common vulnerabilities and response measures for OpenSSL in Debian systems. DebianOpenSSL known vulnerabilities: OpenSSL has experienced several serious vulnerabilities, such as: Heart Bleeding Vulnerability (CVE-2014-0160): This vulnerability affects OpenSSL 1.0.1 to 1.0.1f and 1.0.2 to 1.0.2 beta versions. An attacker can use this vulnerability to unauthorized read sensitive information on the server, including encryption keys, etc.

The article explains how to use the pprof tool for analyzing Go performance, including enabling profiling, collecting data, and identifying common bottlenecks like CPU and memory issues.Character count: 159

The article discusses writing unit tests in Go, covering best practices, mocking techniques, and tools for efficient test management.

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

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. �...

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,...

The article discusses managing Go module dependencies via go.mod, covering specification, updates, and conflict resolution. It emphasizes best practices like semantic versioning and regular updates.

This article introduces a variety of methods and tools to monitor PostgreSQL databases under the Debian system, helping you to fully grasp database performance monitoring. 1. Use PostgreSQL to build-in monitoring view PostgreSQL itself provides multiple views for monitoring database activities: pg_stat_activity: displays database activities in real time, including connections, queries, transactions and other information. pg_stat_replication: Monitors replication status, especially suitable for stream replication clusters. pg_stat_database: Provides database statistics, such as database size, transaction commit/rollback times and other key indicators. 2. Use log analysis tool pgBadg
