Home > other >  How to print all the values of a variable outside a loop?
How to print all the values of a variable outside a loop?

Time:09-06

In this code, I have a function in which I find the users' names. It finds them and prints all the names inside the loop but when I return the s variable outside the loop, it prints only the first name. It does not print all the names.

Although I append s variable in another variable also but still does not work.

type Signup struct {
    Names       string
    Emails     string
}

func FindNames() string {
    db := Connect()
    var s string
    rows, err := db.Query("select names from Signup")
    if err != nil {
        log.Fatal(err)
    } 
    defer rows.Close()

    for rows.Next() {
        var signup Signup
        err := rows.Scan(&signup.Names)
        if err != nil {
            log.Fatal(err)
        }
        // s = signup.Names
        // fmt.Println(s)
        s = fmt.Sprintf("%s", signup.Names)
    }
    return s
}

CodePudding user response:

When looping over stuff it'd make sense to put the results in a list, then do some actions on the results. Or to use a stringbuilder (as it's faster).

Example with list

type Signup struct {
    Names       string
    Emails     string
}

func FindNames() string {
    db := Connect()
    var s string
    rows, err := db.Query("select names from Signup")
    if err != nil {
        log.Fatal(err)
    } 
    defer rows.Close()

    var names []string

    for rows.Next() {
        var signup Signup
        err := rows.Scan(&signup.Names)
        if err != nil {
            log.Fatal(err)
        }
        names = append(names, signup.Names)
    }
    return strings.Join(names, "\n") // newline (\n) character to print multiple lines.
}

Stringbuilder

func FindNames() string {
    db := Connect()
    var s string
    rows, err := db.Query("select names from Signup")
    if err != nil {
        log.Fatal(err)
    } 
    defer rows.Close()

    var sb strings.Builder 

    for rows.Next() {
        var signup Signup
        err := rows.Scan(&signup.Names)
        if err != nil {
            log.Fatal(err)
        }
        sb.WriteString(signup.Names)
        sb.WriteRune('\n')
    }
    return sb.String()
}
  • Related