英文:
Set function parameter types in Go
问题
我是Go编程语言的完全初学者,我正在尝试定义一个名为addStuff
的Go函数的参数类型,该函数简单地将两个整数相加并返回它们的和,但是当我尝试编译该函数时,我看到以下错误:
prog.go:6: undefined: a
prog.go:6: undefined: b
prog.go:7: undefined: a
prog.go:7: undefined: b
prog.go:7: too many arguments to return
prog.go:11: addStuff(4, 5) used as value
以下是产生这个编译器错误的代码:
package main
import "fmt"
import "strconv"
func addStuff(a, b){
return a+b
}
func main() {
fmt.Println("Hello," + strconv.Itoa(addStuff(4,5)))
}
我在这里做错了什么,设置Go中参数类型的正确方法是什么?
英文:
I'm a complete beginner to the Go programming language, and I'm trying to define the parameter types of a Go function called addStuff
that simply adds two integers and returns their sum, but I see the following error when I try to compile the function:
prog.go:6: undefined: a
prog.go:6: undefined: b
prog.go:7: undefined: a
prog.go:7: undefined: b
prog.go:7: too many arguments to return
prog.go:11: addStuff(4, 5) used as value
Here's the code that produced this compiler error:
package main
import "fmt"
import "strconv"
func addStuff(a, b){
return a+b
}
func main() {
fmt.Println("Hello," + strconv.Itoa(addStuff(4,5)))
}
What am I doing wrong here, and what is the correct way to set the types of parameters in Go?
答案1
得分: 30
func addStuff(a int, b int) int {
return a+b
}
这将使a
和b
成为int
类型的参数,并使函数返回一个int
。另一种方式是func addStuff(a, b int) int
,它也会将a
和b
都设置为int
类型的参数。
我强烈推荐A Tour of Go,它教授Go语言的基础知识。
英文:
func addStuff(a int, b int) int {
return a+b
}
This will make a
and b
parameters of type int
, and have the function return an int
. An alternative is func addStuff(a, b int) int
which will also make both a
and b
parameters of type int
.
I highly recommend A Tour of Go which teaches the basics of Go.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论