如何从切片中填充函数参数?

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

How to fill function arguments from slice?

问题

我是你的中文翻译助手,以下是你要翻译的内容:

我是golang的新手,请帮助一个菜鸟。

我正在尝试从数据切片[]interface{}中填充SQL插入语句。为了做到这一点,我需要使用从输入通道获取的切片的各个部分作为参数调用sql包的Exec函数。

最好通过以下代码片段展示问题:

// 构建具有可变列数的INSERT语句
insertSql := "INSERT INTO " + database + "." + table + " VALUES ("
first := true
for _ = range format {
    if !first {
        insertSql += ","
    }
    first = false
    insertSql += "?"
}
insertSql += ")"

// 准备语句
stm, err := db.Prepare(insertSql)
if err != nil {
    return err
}

// 使用通过inputCh接收到的数据(类型为[]interface{})执行语句
outerLoop:
for {
    select {
    case data, opened := <-inputCh:
        if !opened {
            break outerLoop
        }

        // 需要将类型为[]interface{}的数据转换为Exec的各个参数
        _, err := stm.Exec(XXXXXXX)
        if err != nil {
            return err
        }
    }
}

请提供XXXXXXX部分的代码,以便我可以帮助你进行翻译。

英文:

I'm new to golang, pls help a noob.

I'm trying to fill a SQL insert statement from slice of data []interface{}. In order to do that I need to call Exec function of sql package with arguments which are individual parts of slice I get from input channel.

Best to show piece of code in question:

<!-- language: lang-go -->

// build INSERT vith variable number of columnes to fill
insertSql := &quot;INSERT INTO &quot; + database + &quot;.&quot; + table + &quot; VALUES (&quot;
first := true
for _ = range format {
    if !first {
        insertSql += &quot;,&quot;
    }
    first = false
    insertSql += &quot;?&quot;
}
insertSql += &quot;)&quot;

// prepare statment
stm, err := db.Prepare(insertSql)
if err != nil {
    return err
}

// execute the statement with data received via inputCh (type: []interface{})
outerLoop:
for {
    select {
        case data, opened := &lt;-inputCh:
            if !opened {
                break outerLoop
            }

        // need to convert data of type []interface{} to individual arguments for Exec
        _, err := stm.Exec(XXXXXXX)
        if err != nil {
            return err
        }
    }
}

答案1

得分: 2

你需要将...标记添加到你的切片中。有关可变参数的更多详细信息,请参阅关于可变参数的文档

英文:

You have to append the ... token to your slice. See the documentation about variadic parameters for more details.

huangapple
  • 本文由 发表于 2014年7月27日 04:29:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/24975259.html
匿名

发表评论

匿名网友

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

确定