在线观看不卡亚洲电影_亚洲妓女99综合网_91青青青亚洲娱乐在线观看_日韩无码高清综合久久

鍍金池/ 問答/GO/ Go語言圣經(jīng)中函數(shù)調(diào)用的疑問

Go語言圣經(jīng)中函數(shù)調(diào)用的疑問

cf/main.go
// Copyright ? 2016 Alan A. A. Donovan & Brian W. Kernighan.
// License: https://creativecommons.org/l...

// See page 43.
//!+

// Cf converts its numeric argument to Celsius and Fahrenheit.
package main

import (

"fmt"
"os"
"strconv"

"gopl.io/ch2/tempconv"

)

func main() {

for _, arg := range os.Args[1:] {
    t, err := strconv.ParseFloat(arg, 64)
    if err != nil {
        fmt.Fprintf(os.Stderr, "cf: %v\n", err)
        os.Exit(1)
    }
    f := tempconv.Fahrenheit(t)
    c := tempconv.Celsius(t)
    fmt.Printf("%s = %s, %s = %s\n",
        f, tempconv.FToC(f), c, tempconv.CToF(c))
}

}

//!-

tempconv/tempconv.go
// Copyright ? 2016 Alan A. A. Donovan & Brian W. Kernighan.
// License: https://creativecommons.org/l...

//!+

// Package tempconv performs Celsius and Fahrenheit conversions.
package tempconv

import "fmt"

type Celsius float64
type Fahrenheit float64

const (

AbsoluteZeroC Celsius = -273.15
FreezingC     Celsius = 0
BoilingC      Celsius = 100

)

func (c Celsius) String() string { return fmt.Sprintf("%g°C", c) }
func (f Fahrenheit) String() string { return fmt.Sprintf("%g°F", f) }

//!-

tempconv/conv.go
// Copyright ? 2016 Alan A. A. Donovan & Brian W. Kernighan.
// License: https://creativecommons.org/l...

// See page 41.

//!+

package tempconv

// CToF converts a Celsius temperature to Fahrenheit.
func CToF(c Celsius) Fahrenheit { return Fahrenheit(c*9/5 + 32) }

// FToC converts a Fahrenheit temperature to Celsius.
func FToC(f Fahrenheit) Celsius { return Celsius((f - 32) * 5 / 9) }

//!-

上面程序中的
f := tempconv.Fahrenheit(t)
c := tempconv.Celsius(t)
是怎么調(diào)用的以下方法呢:
func (c Celsius) String() string { return fmt.Sprintf("%g°C", c) }
func (f Fahrenheit) String() string { return fmt.Sprintf("%g°F", f) }
這兩個方法都是有函數(shù)名String的。不太明白這個調(diào)用過程。

回答
編輯回答
維他命

func (c Celsius) String() string { return fmt.Sprintf("%g°C", c) }
func (f Fahrenheit) String() string { return fmt.Sprintf("%g°F", f) }
這兩個方法分別是新定義的Celsius與Fahrenheit類型的"toString()方法(Java中這樣)" C#中叫"ToString()",打印此類的對象會自動調(diào)用這個方法

一開始我也看不懂,語法比較怪異. 我想是因?yàn)閠ype定義類只是一句話,沒有類體,所以此類的"String方法"只能獨(dú)立存在了。但獨(dú)立存在總得標(biāo)識下是屬性于哪個類的吧,所以在方法名前放一個某類的對象(f Celsius),哪個對象調(diào)用String()方法這個f就是那個對象。

2017年12月10日 09:21
編輯回答
綰青絲

許多類型都會定義一個String方法,因?yàn)楫?dāng)使用fmt包的打印方法時(shí),將會優(yōu)先使用該類型對應(yīng)的String方法返回的
結(jié)果打印
我明白了。。

2018年9月3日 20:26