首页 > 其他分享 >0086-Go-可变参数函数

0086-Go-可变参数函数

时间:2022-10-30 08:35:17浏览次数:74  
标签:nums fmt num 可变 Go 0086 total sum

环境

  • Time 2022-08-23
  • Go 1.19

前言

说明

参考:https://gobyexample.com/variadic-functions

目标

使用 Go 语言的可变参数函数。

可变参数函数

package main

import "fmt"

func sum(nums ...int) {
	fmt.Print(nums, " ")
	total := 0

	for _, num := range nums {
		total += num
	}
	fmt.Println(total)
}

func main() {

	sum(1, 2)
	sum(1, 2, 3)
}

切片

package main

import "fmt"

func sum(nums ...int) {
	fmt.Print(nums, " ")
	total := 0

	for _, num := range nums {
		total += num
	}
	fmt.Println(total)
}

func main() {
	nums := []int{1, 2, 3, 4}
	// 切片需要先转换
	sum(nums...)
}

总结

使用 Go 语言的可变参数函数。

附录

标签:nums,fmt,num,可变,Go,0086,total,sum
From: https://www.cnblogs.com/jiangbo4444/p/16840456.html

相关文章

  • 0087-Go-闭包
    环境Time2022-08-23Go1.19前言说明参考:https://gobyexample.com/closures目标使用Go语言的闭包。示例packagemainimport"fmt"funcintSeq()func()i......
  • 0088-Go-递归
    环境Time2022-08-23Go1.19前言说明参考:https://gobyexample.com/closures目标使用Go语言的递归。递归函数packagemainimport"fmt"funcfact(nint)i......
  • 0089-Go-指针
    环境Time2022-08-23Go1.19前言说明参考:https://gobyexample.com/pointers目标使用Go语言的指针。示例packagemainimport"fmt"funczeroval(ivalint)......
  • 0090-Go-字符串
    环境Time2022-08-23Go1.19前言说明参考:https://gobyexample.com/strings-and-runes目标使用Go语言的字符串。字节遍历packagemainimport"fmt"funcma......
  • 0091-Go-结构体
    环境Time2022-08-24Go1.19前言说明参考:https://gobyexample.com/structs目标使用Go语言的结构体。直接使用结构体packagemainimport"fmt"typeperson......
  • 0092-Go-方法
    环境Time2022-08-24Go1.19前言说明参考:https://gobyexample.com/methods目标使用Go语言的方法。值方法packagemainimport"fmt"typerectstruct{......
  • 0093-Go-接口
    环境Time2022-08-24Go1.19前言说明参考:https://gobyexample.com/interfaces目标使用Go语言的接口。定义接口typegeometryinterface{area()float64......
  • 0094-Go-结构体嵌入
    环境Time2022-08-24Go1.19前言说明参考:https://gobyexample.com/struct-embedding目标使用Go语言的结构体嵌入。定义结构体typebasestruct{numint......
  • 0095-Go-泛型
    环境Time2022-08-24Go1.19前言说明参考:https://gobyexample.com/generics目标使用Go语言的泛型。泛型函数packagemainimport"fmt"funcMapKeys[Kcom......
  • 0075-Go-变量
    环境Time2022-08-23Go1.19前言说明参考:https://gobyexample.com/variables目标使用Go语言变量的申明和使用变量。示例packagemainimport"fmt"funcma......