Continuing with variadic functions in Go

Follow the latest of Whizdumb’s journey here.

Now that we know, about variadic functions Lets explore them a little more.

The most common variadic function we have been using all along is fmt.Println().

We can use that function to print just a String.

package main
import "fmt"

func main() {       
    fmt.Println("Hi this is a sample string")  
}


or we can print a string and a float

package main
import "fmt"

func main() {       
    fmt.Println("Hi this is a sample string", 4.5)  
}

or we can print a string, a float and multiple int values

package main
import "fmt"

func main() {       
    fmt.Println("Hi this is a sample string", 4.5, 4,5,6,67,23)  
}

Notice the different types here along with different number of arguments. How does Println function does that?

From the documentation, the println function looks like

func Println(a ...interface{}) (n int, err error)

So it can accept multiple parameters of type interface{}, we will explore interface{} later, but for now lets take it that it allows Println to account for all basic type

It also has 2 return types one int and one error, Here is how they work

package main
import "fmt"
func main() {
    x,y := fmt.Println("Hello, world")
    fmt.Println(x,y)
}

If all goes well the above code prints

Hello, world
13 

Signifying that 13 bytes were written and no error was encountered.

Lets explore another function, lets try to append value of one slice to another slice. We will use builtin append function. The signature of append function looks like

func append(slice []Type, elems ...Type) []Type

It accepts a slice as a first argument and thereafter variable number of arguments. But how can we use it to append one slice to another. We can explode the second slice to append it behind the first. Here is how to do it

package main
import "fmt"
func main() {
     x := []int{
    48,96,86,68,
    57,82,63,70,
    37,34,83,27,
    19,97, 9,17,
}   

  y := []int{
    48,96,86,68,
    57,82,63,70,
    37,34,83,27,
    19,97, 9,17,
}   

   z:= append(x,y...)
   fmt.Println(z)

}

Notice the line z:= append(x,y…) . The … behind slice y are very important since they tell the compiler to actually explode the slice and pass in each value as a parameter to the function. The output from above code is

[48 96 86 68 57 82 63 70 37 34 83 27 19 97 9 17 48 96 86 68 57 82 63 70 37 34 83 27 19 97 9 17]

Later!

~~ Whizdumb ~~

Advertisements