Menu
×
   ❮   
HTML CSS JAVASCRIPT SQL PYTHON JAVA PHP HOW TO W3.CSS C C++ C# BOOTSTRAP REACT MYSQL JQUERY EXCEL XML DJANGO NUMPY PANDAS NODEJS R TYPESCRIPT ANGULAR GIT POSTGRESQL MONGODB ASP AI GO KOTLIN SASS VUE DSA GEN AI SCIPY AWS CYBERSECURITY DATA SCIENCE
     ❯   

Go 函数参数和实参


参数和实参

信息可以作为参数传递给函数。参数在函数内部充当变量。

参数及其类型在函数名称之后、括号内指定。您可以添加任意数量的参数,只需用逗号分隔即可。

语法

func FunctionName(param1 type, param2 type, param3 type) {
  // 要执行的代码
}

带参数的函数示例

以下示例具有一个带有一个参数(fname)的函数,该参数的类型为 string。当调用 familyName() 函数时,我们还会传递一个名称(例如 Liam),并且该名称在函数内部使用,该函数输出几个不同的名字,但姓氏相同。

示例

package main
import ("fmt")

func familyName(fname string) {
  fmt.Println("Hello", fname, "Refsnes")
}

func main() {
  familyName("Liam")
  familyName("Jenny")
  familyName("Anja")
}

结果

Hello Liam Refsnes
Hello Jenny Refsnes
Hello Anja Refsnes
自己尝试一下 »

注意:当将参数传递给函数时,称为实参。因此,从上面的示例中:fname 是一个参数,而 LiamJennyAnja实参



多个参数

在函数内部,您可以添加任意数量的参数。

示例

package main
import ("fmt")

func familyName(fname string, age int) {
  fmt.Println("Hello", age, "year old", fname, "Refsnes")
}

func main() {
  familyName("Liam", 3)
  familyName("Jenny", 14)
  familyName("Anja", 30)
}

结果

Hello 3 year old Liam Refsnes
Hello 14 year old Jenny Refsnes
Hello 30 year old Anja Refsnes
自己尝试一下 »

注意:当您使用多个参数时,函数调用必须与参数数量相同的实参,并且实参必须按相同的顺序传递。


×

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail:
[email protected]

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail:
[email protected]

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

Copyright 1999-2024 by Refsnes Data. All Rights Reserved. W3Schools is Powered by W3.CSS.