Home Backend Development Golang How to pass indefinite parameters in golang

How to pass indefinite parameters in golang

Dec 23, 2019 am 10:36 AM
indefinite parameters

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)
Copy after login

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
}
Copy after login

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
}
Copy after login

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)
Copy after login

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)等价
Copy after login

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}
Copy after login

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...) // 编译无法通过
Copy after login

You will see an error message like this:

cannot use arr (type [5]int) as type []int in argument to sum
Copy after login

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...) // 无法通过编译
Copy after login

This time you will see a relatively long error message:

too many arguments in call to sum
    have (number, []int...)
    want (...int)
Copy after login

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!

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
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 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)

What are the vulnerabilities of Debian OpenSSL What are the vulnerabilities of Debian OpenSSL Apr 02, 2025 am 07:30 AM

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.

How do you use the pprof tool to analyze Go performance? How do you use the pprof tool to analyze Go performance? Mar 21, 2025 pm 06:37 PM

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

How do you write unit tests in Go? How do you write unit tests in Go? Mar 21, 2025 pm 06:34 PM

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

What libraries are used for floating point number operations in Go? What libraries are used for floating point number operations in Go? Apr 02, 2025 pm 02:06 PM

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

What is the problem with Queue thread in Go's crawler Colly? What is the problem with Queue thread in Go's crawler Colly? Apr 02, 2025 pm 02:09 PM

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

Transforming from front-end to back-end development, is it more promising to learn Java or Golang? Transforming from front-end to back-end development, is it more promising to learn Java or Golang? Apr 02, 2025 am 09:12 AM

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

How do you specify dependencies in your go.mod file? How do you specify dependencies in your go.mod file? Mar 27, 2025 pm 07:14 PM

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.

PostgreSQL monitoring method under Debian PostgreSQL monitoring method under Debian Apr 02, 2025 am 07:27 AM

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

See all articles