如何传递空接口

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

How to pass the empty interface

问题

我有一个带有接口作为参数的sqlx查询函数,现在我想使用原始的查询字符串,如何省略这个接口参数?

func QuerySlice(query string, data interface{}) error {
    q := queryString(query, data)
}

// 如果传递数据
data := struct {
    id string `db:"id"`
}{
    Id: id,
}
QuerySlice(query, data)

// 查询的SQL语句是
SELECT
    *
FROM
    table
WHERE
    id = :id

// 现在我想要原始的SQL语句
SELECT
    *
FROM
    table
WHERE
    id = 'XXX'

// 如何传递数据接口以省略此参数?

要省略接口参数,你可以将data参数设置为nil,这样在调用queryString函数时就不会使用它。修改后的代码如下:

func QuerySlice(query string, data interface{}) error {
    q := queryString(query, nil)
}

// 调用时将data参数设置为nil
QuerySlice(query, nil)

这样就可以使用原始的SQL语句进行查询了。

英文:

I have a sqlx query function with interface as passing parameter, now i want to using the raw query string, how to omit this interface parameter?

func QuerySlice(query string, data interface{}) error {
	q := queryString(query, data)
}

// If pass the data
data := struct {
    id string `db:"id"`
}{
	Id: id,
}
QuerySlice(query, data)

// The query sql is
SELECT
	*
FROM
	table
WHERE
	id = :id

// Now i want the raw sql
SELECT
	*
FROM
	table
WHERE
	id = 'XXX'

// How to pass the data interface to omit this parameter

答案1

得分: 2

如果你正在使用NamedExec,你可以将一个空的映射传递给sqlx:

QuerySlice(rawQuery, map[string]interface{}{})
英文:

If you are using NamedExec, you could pass a empty map to sqlx

QuerySlice(rawQuery, map[string]interface{}{})

huangapple
  • 本文由 发表于 2021年10月17日 16:13:15
  • 转载请务必保留本文链接:https://go.coder-hub.com/69602454.html
匿名

发表评论

匿名网友

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

确定