variadic-go

path: courses/go-course/variadic-go.md

- **fileName**: variadic-go
- **Created on**: 2024-09-01 12:35:01

in this go code example how the function can take more than one arguamtments and handle them as one argument this name varidic and using for fmt library for print mulitable words in the example making the append method for slice and handle reallocate process for the slice

package main
import ( "fmt")
func main() {
    // the  make take the type and len and cap 
    // HINT: cap the capacity of the slice mean when the cap is finish there is an operaition for the slice for 
    // reseazing the slice and get the size for the new element
    mySlice := make([]string, 0) // start initalization the slice
    mySlice = append(mySlice, "yossef", "ahmed", "sara") // starting append value using the func append
    PrintUser(mySlice) // using the printUser func to print values
    fmt.Println("\nthe slice size: %d", len(mySlice)) // print the len
    fmt.Println("the slice cap: %d", cap(mySlice)) // print the cap
    return
}

/*
the function append for appending the value in slice and reallocate the slice if there no cap for values
*/
func append(slice []string, value ...string) []string {
    l := len(slice) // geting the slice len
    // starting check if the slice cap end
    if l+len(value) > cap(slice) { // reallocate a new slice an save the new data
        // if end allocate a new size with the double size
        newSlice := make([]string, l+len(value) * 2) 
        copy(newSlice, slice) // copy to the values in slice to new slices
        // and copy the values only not any address

        /*
slice address: 0x23
newSlice address: 0x29
*/

        slice = newSlice // than save the old to be point to the new slice

        /*
slice address: 0x29
newSlice address: 0x29
*/
        // hint : don't bather for the new slice the garpage collaction gone clean it
    }
    // update the len for slice to the new len 
    slice = slice[0:l+len(value)]
    // copy the value to new position
    copy( slice[l:], value)
    return slice
}

/**
for pirnt the slice values
*/
func PrintUser(slice []string) {
    for _, value := range slice {
        fmt.Printf("%s ", value)
    }
}

continue:map-go.md
before:array-slice.md