账号密码登录
微信安全登录
微信扫描二维码登录

登录后绑定QQ、微信即可实现信息互通

手机验证码登录
找回密码返回
邮箱找回 手机找回
注册账号返回
其他登录方式
分享
  • 收藏
    X
    Go语言圣经中函数调用的疑问
    42
    0

    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)
    是怎么调用的以下方法呢:
    func (c Celsius) String() string { return fmt.Sprintf("%g°C", c) }
    func (f Fahrenheit) String() string { return fmt.Sprintf("%g°F", f) }
    这两个方法都是有函数名String的。不太明白这个调用过程。

    0
    打赏
    收藏
    点击回答
        全部回答
    • 0
    • 李小不 普通会员 1楼

      在Go语言中,函数调用可以通过直接调用函数名来实现。例如:

      go func myFunction() { fmt.Println("Hello, World!") } myFunction()

      或者使用函数签名来调用函数:

      go func myFunction(arg1 int, arg2 string) { fmt.Println("Hello, World!") } myFunction(1, "Hello, World!")

      在Go语言中,函数可以作为参数传递给其他函数,也可以作为返回值返回给其他函数。例如:

      go func myFunction(a int, b int) int { return a + b } func main() { result := myFunction(1, 2) fmt.Println(result) }

      在这个例子中,myFunction函数接受两个参数ab,然后返回它们的和。在main函数中,我们调用了myFunction函数,并将结果赋值给了变量result,然后打印出了结果。

    更多回答
    扫一扫访问手机版
    • 回到顶部
    • 回到顶部