将for循环的值作为函数参数传递

huangapple go评论109阅读模式
英文:

Passing for loop values as function parameters

问题

它说:(no value)被用作值,但我正在将循环值从切片传递给它!

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)
}

在Go Playground上查看代码片段

英文:

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

package main

import &quot;fmt&quot;

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

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

func main() {
	cycle([]string{&quot;John&quot;, &quot;Marie&quot;}, greet)
}

Code snippet on Go Playground

答案1

得分: 2

我找到了解决方案:我应该直接调用函数,而不是在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)
}
英文:

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

package main

import &quot;fmt&quot;

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

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

func main() {
	cycle([]string{&quot;John&quot;, &quot;Marie&quot;}, greet)
}

huangapple
  • 本文由 发表于 2022年9月29日 13:24:51
  • 转载请务必保留本文链接:https://go.coder-hub.com/73890640.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定