dougua3705 2016-12-15 08:02
浏览 62
已采纳

为什么不使用%v打印int和字符串

I know to print int we can use %d, and string we can use %s but we can still use %v to print them. So what if I always use %v to print them? What issue will happen if I do this?

  • 写回答

1条回答 默认 最新

  • dtcpvz8162 2016-12-15 08:06
    关注

    Nothing bad will happen, but the %d verb instructs the fmt package to print is as a number (using base 10), and the %v verb means to use the default format which can be overridden.

    See this example:

    type MyInt int
    
    func (mi MyInt) String() string {
        return fmt.Sprint("*", int(mi), "*")
    }
    
    func main() {
        var mi MyInt = 2
        fmt.Printf("%d %v", mi, mi)
    }
    

    Output (try it on the Go Playground):

    2 *2*
    

    When using the %v verb, the fmt package checks if the value implements the fmt.Stringer interface (which is a single String() string method), and if so, that method will be called to convert the value to string (which may be formatted further if flags are specified).

    The complete list of formatting rules is in the package doc of fmt, quoting the relevant part:

    Except when printed using the verbs %T and %p, special formatting considerations apply for operands that implement certain interfaces. In order of application:

    1. If the operand is a reflect.Value, the operand is replaced by the concrete value that it holds, and printing continues with the next rule.

    2. If an operand implements the Formatter interface, it will be invoked. Formatter provides fine control of formatting.

    3. If the %v verb is used with the # flag (%#v) and the operand implements the GoStringer interface, that will be invoked.

    If the format (which is implicitly %v for Println etc.) is valid for a string (%s %q %v %x %X), the following two rules apply:

    1. If an operand implements the error interface, the Error method will be invoked to convert the object to a string, which will then be formatted as required by the verb (if any).

    2. If an operand implements method String() string, that method will be invoked to convert the object to a string, which will then be formatted as required by the verb (if any).

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)
  • ¥15 AIC3204的示例代码有吗,想用AIC3204测量血氧,找不到相关的代码。