I don't understand the paragraph about Variable Functions on the tutorial site called "golang programs"

Asked 2 years ago, Updated 2 years ago, 400 views

If you understand the meaning of the following paragraphs in the Select single arguments from all arguments of variable function. section, please let me know.

Needs to be precede when running an empty function call, if the code inside of the function expecting an argument and presence of argument will generate an error "panic:run-time error:index out of range".Inabove example you have to pass at least 4 arguments>

The problem is the first sentence.Inabove... is self-evident.
I think empty function call means "function call without argument".

Thank you for your cooperation.

go

2022-09-30 22:01

2 Answers

Now let's do it.

https://go.dev/play/p/omWI1XFl5RE

package main

import "fmt"

funcmain(){
    variableExample()
}

func variadicExample(s...string){
    fmt.Println(s[0])
    fmt.Println(s[3])
}

Run Results

 panic:runtime error:index out of range[0] with length0

goroutine1 [running]:
main.variadicExample ({0x0,0x485320,0xc0000001a0})
    /tmp/sandbox399561776/prog.go: 10+0xef
main.main()
    /tmp/sandbox399561776/prog.go: 6+0x25

Program expired.


2022-09-30 22:01

First of all, the sample code says this.
Although variableExample is ready to receive variable length arguments, the implementation is to display the values of the first and fourth arguments in the standard output.

package main

import "fmt"

funcmain(){
    variableExample("red", "blue", "green", "yellow")
}

func variadicExample(s...string){
    fmt.Println(s[0])
    fmt.Println(s[3])
}

Back to the question, the input of the method says that the implementation requires at least four arguments, even though it is a variable length argument, so for example, if you do not give any parameters, it will cause panic.
例 As an example, there are cases with parameters, but as far as the implementation is concerned, there are no two, and even three panics occur

Needs to be precede when running an empty function call, if the code inside of the function expecting an argument and presence of argument will generate an error "panic:run-time error:index out of range".Inabove example you have to pass at least 4 arguments>


2022-09-30 22:01

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.