duannima8347 2017-09-11 03:58
浏览 34
已采纳

为什么以下Go程序需要函数的名称为String()而不是其他名称?

I'm following a book which shows the following example.

package main

import (
    "fmt"
)

const (
    KB = 1024
    MB = 1048576          //KB * 1024
    GB = 1073741824       //MB * 1024
    TB = 1099511627776    //GB * 1024
    PB = 1125899906842624 //TB * 1024
)

type ByteSize float64

func (b ByteSize) String() string {
    switch {
    case b >= PB:
        return "Very Big"
    case b >= TB:
        return fmt.Sprintf("%.2fTB", b/TB)
    case b >= GB:
        return fmt.Sprintf("%.2fGB", b/GB)
    case b >= MB:
        return fmt.Sprintf("%.2fMB", b/MB)
    case b >= KB:
        return fmt.Sprintf("%.2fKB", b/KB)
    }
    return fmt.Sprintf("%dB", b)
}

func main() {
    fmt.Println(ByteSize(2048))
    fmt.Println(ByteSize(3292528.64))
}

When I run this program it gives me the following output (in human readable data size units).

2.00KB
3.14MB

But when I change the name of the function called String() to anything else, or if I lower-case the S in String, it gives me the following output.

2048
3.29252864e+06

What is the reason behind that? Is there some String() function attached to some interface and our ByteSize type satisfies that interface? I mean what the hell?

  • 写回答

3条回答 默认 最新

  • ds000001 2017-09-11 04:00
    关注

    When you define a method named String with no parameters returning a string, you implement the Stringer interface, which is documented here: https://golang.org/pkg/fmt/#Stringer.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 抖音咸鱼付款链接转码支付宝
  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 求螺旋焊缝的图像处理
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?
  • ¥15 网络通信安全解决方案
  • ¥50 yalmip+Gurobi
  • ¥20 win10修改放大文本以及缩放与布局后蓝屏无法正常进入桌面
  • ¥15 itunes恢复数据最后一步发生错误
  • ¥15 关于#windows#的问题:2024年5月15日的win11更新后资源管理器没有地址栏了顶部的地址栏和文件搜索都消失了