Home > Net >  Using Go to avoid duplicates from existing array data when appending slices with user input
Using Go to avoid duplicates from existing array data when appending slices with user input

Time:10-18

Forgive all my comments, I'm learning and that keeps me straight. Looking for a better solution to my conditional statement near the bottom and provided the rest for context. Tried out the loop comment suggested, but still not getting the right result as written here

// define the main package file
package main

//importing formatting features for the user I/O and string manipulation packages
//Parenthesis not needed if only importing 1 package
import (
    "fmt"
    "strings"
)

// defining the main function of the standalone app
func main() {

    //initializing a string array
    options := []string{"lemon", "orange", "strawberry", "banana", "grape"}

    //creating a slice in the array to designate favorites
    favFruits := options[0:3]
    fmt.Println(options)

    //initializing variable for user input
    var fruit string
    fmt.Print("Favorite Fruit Not Listed: ")
    fmt.Scan(&fruit)

    //convert response to lowercase
    fruitConv := strings.ToLower(fruit)

    //conditional statement example
    for _, pick := range options {
        if pick == fruitConv {
            fmt.Println("You were supposed to pick something else")
            break
        } else {
            fmt.Println("Response Accepted!")
            break
        }
        break
    }
    //adding user inputed favorite fruit to the sliced array
    favFruits = append(favFruits, fruitConv)
    fmt.Print(favFruits)

}

CodePudding user response:

I got your point. If you go to official Go packages section you will get slices package over there. Ref: slices

There is one function named contains inside the slices package, you can make use of that function. For your simplicity, I have created one example matching with your scenario.

func main() {

    //initializing a string array
    options := []string{"lemon", "orange", "strawberry", "banana", "grape"}

    // assuming fruit as user input
    fruit := "lemon"

    //conditional statement example
    if fruit == "coconut" || fruit == "coconuts" {
        fmt.Println("Coconuts are nasty (except on your hair/skin)")

        //**there has to be a way to simplify this code if the array grows server-side or something**
    } else if slices.Contains(options, fruit) {
        fmt.Println("You were supposed to pick something different...")
    }
}

Here is the working link :- https://goplay.tools/snippet/bzSm_biR4Vr

Note: Since in your scenario there is lot of such contain checks, I would recommend to use map instead of slice. Internally if you deep dive in conatins function of slice you will get to know.

  • Related