N
N
NOONE2018-12-04 13:51:36
go
NOONE, 2018-12-04 13:51:36

Why doesn't the example work?

Hello, I'm reading a book on GO by Donovan.A Kernighan.B, section 2.5 Type casting, there is an example from the book about temperature conversion

package main

import (
  "fmt"
)


type Celsius float64 
type Fahrenheit float64

var c Celsius
var f Fahrenheit

const (
AbsoluteZeroC Celsius = -273.15 
FreezingC Celsius = 0 
BoilingC Celsius = 100
)

func (с Celsius) String() string { 
return fmt.Sprintf("%g°C", c) 
}
func FToC(f Fahrenheit) Celsius { 
return Celsius((f - 32) * 5 / 9) 
}


func CToF(c Celsius) Fahrenheit { 
return Fahrenheit(c*9/5 + 32) 
}

func main() {
c := FToC(212.0)
fmt.Println(c.String())
}

In theory, when calling c := FToC(212.0) - we should get the temperature in Celsius, i.e. 100C, but in the end I get 0, the book has the same example and everything works there. Looking at the code, I don’t see any obvious problem, I already twisted / smoked the code and didn’t understand what the plug was, Can someone throw a hint where my jamb is

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander Pavlyuk, 2018-12-04
@Djam36

Here "c" is a Russian character, where (c Celsius)
And in fmt.Sprintf("%g°C", c) is already English, so not a type value is returned, but a global variable c, which is unclear why you have declared generally.

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

Should be like this: https://play.golang.org/p/WH2G3yMiA4o

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question