谁在定义用于类型转换的Get()方法? 高朗本身?

SEE: // Defines a method "Get() uint64" for value Binary func (i Binary) Get() uint64 { return uint64(i) }

We define a method Get() and apparently b := Binary(200) executes it, but where is the connection between then. I have not found where Get() is defined and I assume that this definition is overlaying an internal definition, or am I wrong.


package main

import (
    "fmt"
    "strconv"
)

// This defines a interface with one method: "String() string"
type Stringer interface {
    String() string
}

// Defines an unsigned 64 bit number
type Binary uint64

// Defines a method "String() string" for value Binary
func (i Binary) String() string {
    return strconv.FormatUint(i.Get(), 2)
}

// Defines a method "Get() uint64" for value Binary
func (i Binary) Get() uint64 {
    return uint64(i)
}

// Main program
func main() {
    b := Binary(200) // Create Unsigned value of 200

    s := Stringer(b) // Calls interface "Stringer" on "b"

    fmt.Println(s.String()) // "s" is an Stringer Interface Type
}

Actually, you have created an alias for uint64, so when you cast the number 200, its primitive value is still a uint64, but your custom Binary type allows you to spruce it up with methods that you can define on your custom type.

The Get() method isn't being called when you cast, you're just telling Go runtime to treat this as a Binary type rather than a base uint64. In fact, the Get() method is actually redundant as you could just pass this around as if it were a uint64 and you didn't have the String() method for satisfying the stringer interface the primitive value will be printed out if you did fmt.Println(b)

fmt.Println(200) //prints 200
fmt.Println(Binary(200)) // also prints 200

As JimB said, This won't occur with the String method defined.

To clarify further, the Get method is being utilized by the String() method which is needed for this type to satisfy the Stringer interface requirement. When you use a function or method that utilizes a Stringer, this is where String() and hence Get() are called. If this is still wrong let me know asap in comments