Golang variable Parameters

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.

The day before yesterday colleague mentioned an example, about the use of variable parameters in Golang, usually do not pay attention to this detail, first on the code bar.


Test code

The code logic you want to implement is clear.

1. Testargs accepts an int parameter, an indefinite length argument, and a type of interface{}

2. Nums as slice, use ... After the grammatical sugar is beaten, afferent Testargs

It looks like logic's fine, do the error.

# command-line-arguments

./test.go:13:cannot use Nums (Type []int64) as type []interface {} ' argument to Testargs

Unexpectedly the type does not match, write Go also a year, this piece of cognition is too not in place, always think will nums, and then to interface{} This common type composition interface{} slice to Testargs.

So, let's see what happens when the nums goes in:


Slice

After executing the output []interface {}, the confirmation is to pass the variable parameter as slice to the function, which is similar to Python. Let's see if slice is the same one.


Fetch Address

After execution the output is as follows

Main addr of Slice 0xc82000c0c0

Testargs addr of Slice 0xc82000c0c0

The same address, if the variable parameter passed in itself is by slice ... form, then use the slice directly, and you will not create a new slice. So I understand the variable-parameter execution of Go:

for func (first int, arg ... T

1. When the variable parameter is not passed, the corresponding Arg is nil

2. When passing a single mutable parameter, actually executes [] T{ARG1,ARG2,ARG3}

3. Incoming ... The slice of the grammatical sugars, use this slice directly

This is why we understand why the small example of the opening is not executed, []int64 and []interface{} are two types of slice.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.