gpt4 book ai didi

go - 具有非固定类型参数的函数

转载 作者:IT王子 更新时间:2023-10-29 02:05:44 25 4
gpt4 key购买 nike

GoLang 中是否可行:

func funcWithDynamicTypeArgs(param notFixedType) 
{

}

我希望 paramintstringmap 以及任何类型。换句话说:是否可以在 Go 中声明和使用带有动态类型参数的 function

最佳答案

例如,

func function(param interface{}) {
}

The Go Programming Language Specification

Interface types

All types implement the empty interface:

interface{}

Type assertions

For an expression x of interface type and a type T, the primary expression

x.(T)

asserts that x is not nil and that the value stored in x is of type T. The notation x.(T) is called a type assertion.


参见 package fmt使用 package reflect处理任何类型的参数。例如,

func Print

func Print(a ...interface{}) (n int, err error)

Print formats using the default formats for its operands and writes to standard output. Spaces are added between operands when neither is a string. It returns the number of bytes written and any write error encountered.

关于go - 具有非固定类型参数的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26835981/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com