英文:
How can i call functions on Golang?
问题
我几天前开始编码,现在不知道如何调用我现在创建的小项目中的函数。这是一个简单的问题,但我很困扰。我将在下面留下我的代码,谢谢!
package main
import "fmt"
func law(grade int) (mathews, john int) {
mathews = 65
john = 69
grade = 70
return
}
func main() {
mathews, john := law(70)
if mathews < grade {
fmt.Println("Mathews,你不能加入哈佛大学。")
} else {
fmt.Println("恭喜,Mathews。你通过了!")
}
if john < grade {
fmt.Println("John,你不能加入哈佛大学。")
} else {
fmt.Println("恭喜,John。你通过了!")
}
}
你需要在 main
函数中调用 law
函数,并将返回的值赋给 mathews
和 john
变量。然后,你可以使用这些变量进行条件判断和打印输出。希望对你有帮助!
英文:
I started coding a few days ago and I don't know how to call functions for a small project that I create now. It's a simple question but I'm struggling a lot. I will leave my code below, thank you!
package main
import "fmt"
func law(grade int) (mathews, john int) {
mathews = 65
john = 69
grade = 70
return
}
func main() {
law()
if mathews < grade {
fmt.Println("Mathews, you are not allow to join on Harvard.")
} else {
fmt.Println("Congratulations, Mathews. You passed!")
}
if john < grade {
fmt.Println("John, you are not allow to join on Harvard.")
} else {
fmt.Println("Congratulations, John. You passed!")
}
}
答案1
得分: 1
有多个问题:
- 你的函数
law
有一个参数grade
,但是在调用函数时没有提供该参数。 - 当你调用函数时,你需要将函数返回的结果存储在一个变量中。
尝试像这样做:
package main
import "fmt"
func law(grade int) (mathews, john int) {
mathews = 65
john = 69
grade = 70 // 这一行没有起作用,所以你应该将其删除。
return
}
func main() {
grade := 70
mathews, john := law(grade)
if mathews < grade {
fmt.Println("Mathews,你不能加入哈佛大学。")
} else {
fmt.Println("恭喜,Mathews。你通过了!")
}
if john < grade {
fmt.Println("John,你不能加入哈佛大学。")
} else {
fmt.Println("恭喜,John。你通过了!")
}
}
在A Tour of Go
中查看函数的使用方法:https://tour.golang.org/basics/4。
英文:
There are multiple issue:
- Your function
law
has an argumentgrade
but you are not providing that argument when you are calling the function. - When you call the function you need to store whatever is returned by the function in a variable.
Try something like this
package main
import "fmt"
func law(grade int) (mathews, john int) {
mathews = 65
john = 69
grade = 70 // This line is not doing anything so you should actually remove it.
return
}
func main() {
grade := 70
mathews, john := law(grade)
if mathews < grade {
fmt.Println("Mathews, you are not allow to join on Harvard.")
} else {
fmt.Println("Congratulations, Mathews. You passed!")
}
if john < grade {
fmt.Println("John, you are not allow to join on Harvard.")
} else {
fmt.Println("Congratulations, John. You passed!")
}
}
Checkout functions in A Tour of Go
: https://tour.golang.org/basics/4 for a basic run through on how to use functions in Go.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论