doulun5683 2013-12-14 07:19
浏览 62
已采纳

如何使用扫描界面将从数据库读取的字符串转换为小写

I want to lower case a string as I read it in from the database. I know this can be done in SQL, but this is my first day with go and this is more of a proof of concept (and understanding of go) rather than an actual requirement.

type EmailAddress should always be lowercase when read from the db using the Scan interface, this breaks with panic: interface conversion: interface is []uint8, not string

package main

import (
  "database/sql"
  "github.com/kisielk/sqlstruct"
  _ "github.com/lib/pq"
  "log"
  "strings"
)

type EmailAddress string

func (g *EmailAddress) Scan(src interface{}) error {
  *g = EmailAddress(strings.ToLower(src.(string)))
  return nil
}

type User struct {
  Id          int
  MobilePhone string `sql:"mobile_phone"`
  Email       EmailAddress
}

func main() {
  db, _ := sql.Open("postgres", "host=localhost dbname=test sslmode=disable")
  defer db.Close()

  rows, _ := db.Query("SELECT id, mobile_phone, COALESCE(email,'') as email FROM users limit 5")

  for rows.Next() {
    var t User
    _ = sqlstruct.Scan(&t, rows)
    log.Printf("%+v
", t)
  }
}
  • 写回答

1条回答 默认 最新

  • dongyi8795 2013-12-14 11:07
    关注

    You're seeing the []uint8 error because the EmailAddress is being provided as a byte slice, rather than a string. Remember, byte is just an alias for uint8. Here's a simple example which shows the error you're seeing: http://play.golang.org/p/iN5y3PaFAL

    So, the easiest fix would be to change the scan function:

    func (g *EmailAddress) Scan(src interface{}) error {
      b, ok := src.([]byte)
      if !ok {
        return fmt.Errorf("expected []byte, got %T", src)
      }
      *g = EmailAddress(strings.ToLower(string(b))
      return nil
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 在获取boss直聘的聊天的时候只能获取到前40条聊天数据
  • ¥20 关于URL获取的参数,无法执行二选一查询
  • ¥15 液位控制,当液位超过高限时常开触点59闭合,直到液位低于低限时,断开
  • ¥15 marlin编译错误,如何解决?
  • ¥15 有偿四位数,节约算法和扫描算法
  • ¥15 VUE项目怎么运行,系统打不开
  • ¥50 pointpillars等目标检测算法怎么融合注意力机制
  • ¥20 Vs code Mac系统 PHP Debug调试环境配置
  • ¥60 大一项目课,微信小程序
  • ¥15 求视频摘要youtube和ovp数据集