简体   繁体   中英

Passing for loop values as function parameters

It says: (no value) used as value, but I'm passing loop values from a slice to it!

package main

import "fmt"

func greet(n string) {
    fmt.Printf("Hi, %v\n", n)
}

func cycle(n []string, f func(string)) {
    for i := 0; i < len(n); i++ {
        fmt.Println(f(n[i]))
    }
}

func main() {
    cycle([]string{"John", "Marie"}, greet)
}

Code snippet on Go Playground

I found the solution: I should have called the function directly, not inside Println().

package main

import "fmt"

func greet(n string) {
    fmt.Printf("Hi, %v\n", n)
}

func cycle(n []string, f func(string)) {
    for i := 0; i < len(n); i++ {
        f(n[i])
    }
}

func main() {
    cycle([]string{"John", "Marie"}, greet)
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM