2019-03-28 11:56
浏览 39


Consider the following example:

package main

import (
    _ ""

type Data struct {
    Stuff string

func main() {
    db, _ := sqlx.Connect("mysql", "root:root@(localhost:3306)/data")
    var datas []Data
    db.Select(&datas, "select 'a,b' stuff from data limit 10")

What I'd like to do is have Stuff as []string, where it would be split by ,. I guess I could add an extra []string field and loop over the results populating this field and removing the source data, but that seems inefficient. What's the canonical way to do this in sqlx?

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • duancao1951 2019-03-28 15:00

    While this is not supported out of the box you can create custom struct implementing Scanner interface (

    type StringList []string
    // Scan implements Scanner interface and parses 
    // database result to StringList struct.
    func (s *StringList) Scan(src interface{}) error {
        var source string
        switch src.(type) {
        case string:
            source = src.(string)
        case []byte:
            source = string(src.([]byte))
            return errors.New("Incompatible type for StringList")
        *s = strings.Split(source, ",")
        for i := range *s {
            (*s)[i] = strings.TrimSpace((*s)[i])
        return nil

    And use this struct instead of string:

    type Data struct {
        Stuff StringList
    解决 无用
    打赏 举报

相关推荐 更多相似问题