variadic function _ golang

Variadic functions can be called with any number of trailing arguments. For example, fmt.Println is a common variadic function

package main

import (
    "fmt"
)

func sum(nums ...int) {
    fmt.Println(nums, " ")
    total := 0
    for _, num := range nums {
        total += num
    }
    fmt.Println(total)
}

func main() {

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

    nums := []int{1, 2, 3, 4}
    sum(nums...)
}
[1 2]
3
[1 2 3]
6
[1 2 3 4]
10

总结 :

  1 : ....

时间: 2024-11-06 03:43:51

variadic function _ golang的相关文章

[C++] Template Function _ Any number of parameters

Template Function _ Any number of parameters 1 #include<iostream> 2 #include<cstdarg> 3 using namespace std; 4 5 template <typename T> 6 T getResult(int count,...) 7 { 8 va_list arg_ptr;// the pointer of arguments list 9 va_start(arg_ptr

可变参数的函数(variadic function)的陷阱

1,介绍variadic function 可变参数的函数就是参数数量可以改变的函数.例如printf(): int printf(const char *format, ...); printf("%d%s\n",i,s); C语言之所以可以支持可变参数函数,一个重要的原因是C调用规范中规定C语言函数调用时,参数是从右向左压入栈的:这样一个函数实现的时候,就无需关心调用他的函数会传递几个参数过来,而只要关心自己用到几个:例子: #include<stdarg.h> voi

variadic function 的使用

最近在看<the c programming language> K&R 7.3章 Variable-length Argument Lists  变长参数列表, 笔记一下用法 1. 要用到的头文件  <stdarg.h> 包含一些用来遍历(step through)变长参数列表的  宏(marco)定义 2. 类型 va_list : refer to each argument in turn (va 是 variadic arguments的缩写) va_list a

errors _ golang

In Go it's idiomatic to communicate errors via an explicit, separate return value. this constrasts errors via an explicit, separate return value. This constrasts with the exceptions used in languages like Java and Ruby and the overloaded single resul

multiple return values _ golang

Go has built-in support for multiple return values. This feature is used often in idiomatic Go, for example to return both result and error values from a function package main import ( "fmt" ) func vals() (int, int) { return 3, 7 } func main() {

closures _ golang

Go supports anonymous functions, which can form closures. Anonymous functions are useful when you want to define a function inline without having to name it package main import ( "fmt" ) func intSeq() func() int { i := 0 return func() int { i +=

if else _ golang

if else 在 golang package main import ( "fmt" ) func main() { if 7%2 == 0 { fmt.Println("7 is even") } else { fmt.Println("7 is odd") } if 8%4 == 0 { fmt.Println("8 is divisible by 4") } if num := 9; num < 0 { fmt

for _ golang

for 是 golang 唯一的 looping 结构, package main import ( "fmt" ) func main() { i := 1 for i <= 3 { fmt.Println(i) i += 1 } for j := 7; j <= 9; j++ { fmt.Println(j) } for { fmt.Println("loop") break } } 1 2 3 7 8 9 loop 总结 : 对于这个, 额, 我觉

constants _ golang

golang 中支持 长量 const or static package main import ( "fmt" "math" ) const s string = "constant" const a = 3000 func main() { const s = 3000 fmt.Println(s) const n = (3e8 / s) fmt.Println(n) fmt.Println(int64(n)) fmt.Println(ma