在Go中设置函数参数类型

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

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
}

这将使ab成为int类型的参数,并使函数返回一个int。另一种方式是func addStuff(a, b int) int,它也会将ab都设置为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.

huangapple
  • 本文由 发表于 2013年5月30日 03:18:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/16822137.html
匿名

发表评论

匿名网友

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

确定