V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
The Go Programming Language
http://golang.org/
Go Playground
Go Projects
Revel Web Framework
kkfnui

golang slice vs Python 字符日 使用方便度

  •  
  •   kkfnui ·
    kkfnui · Mar 13, 2018 · 1850 views
    This topic created in 2971 days ago, the information mentioned may be changed or developed.

    使用过一段时间 python

    今天在写 golang 处理日志,发现异常数据超过数据库字段最大长度限制。 写 python 的时候可以直接:

    foo[:32]
    

    golang 中就会存在问题。如果字符串长度不超过 32,则会直接抛出错误。

    golang 写起来还是复杂很多。

    自己再加个辅助函数,就是代码又变长了

    
    // GetStringByLimit 如果字符串长度超过 limit, 截取字符串
    func GetStringByLimit(foo string, limit int) string {
    	if len(foo) > limit {
    		return foo[:limit]
    	}
    	return foo
    }
    
    
    2 replies    2018-03-16 09:37:10 +08:00
    timonwong
        1
    timonwong  
       Mar 15, 2018   ❤️ 1
    golang string 是 utf-8 字符串,你这样截断是没有考虑多字节情况的
    kkfnui
        2
    kkfnui  
    OP
       Mar 16, 2018 via Android
    @timonwong 多谢提醒
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   2702 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 37ms · UTC 14:35 · PVG 22:35 · LAX 07:35 · JFK 10:35
    ♥ Do have faith in what you're doing.