Skip to main content
Title. Link to the exercise.
Source Link
200_success
  • 144.2k
  • 22
  • 188
  • 473

A Tour of Go, problem #56 - method implementationerror handling

New to Go, trying to see ifsolve Tour of Go, Exercise 56, which is about error handling.

Can the following error handling method can be further improved?

package main

import (
    "fmt"
    "math"
)

type ErrNegativeSqrt float64

func (e ErrNegativeSqrt) Error() string {
    return fmt.Sprintf("cannot Sqrt negative number: %f", float64(e))
}

func Sqrt(f float64) (float64, error) {
    if f > 0 {
        return math.Sqrt(f), nil
    } else {
        return 0, ErrNegativeSqrt(f)
    }
}

func main() {
    fmt.Println(Sqrt(2))
    fmt.Println(Sqrt(-2))
}

A Tour of Go, problem #56 - method implementation

New to Go, trying to see if the following error handling method can be further improved?

package main

import (
    "fmt"
    "math"
)

type ErrNegativeSqrt float64

func (e ErrNegativeSqrt) Error() string {
    return fmt.Sprintf("cannot Sqrt negative number: %f", float64(e))
}

func Sqrt(f float64) (float64, error) {
    if f > 0 {
        return math.Sqrt(f), nil
    } else {
        return 0, ErrNegativeSqrt(f)
    }
}

func main() {
    fmt.Println(Sqrt(2))
    fmt.Println(Sqrt(-2))
}

A Tour of Go, problem #56 - error handling

New to Go, trying to solve Tour of Go, Exercise 56, which is about error handling.

Can the following error handling method can be further improved?

package main

import (
    "fmt"
    "math"
)

type ErrNegativeSqrt float64

func (e ErrNegativeSqrt) Error() string {
    return fmt.Sprintf("cannot Sqrt negative number: %f", float64(e))
}

func Sqrt(f float64) (float64, error) {
    if f > 0 {
        return math.Sqrt(f), nil
    } else {
        return 0, ErrNegativeSqrt(f)
    }
}

func main() {
    fmt.Println(Sqrt(2))
    fmt.Println(Sqrt(-2))
}
edited tags
Link
200_success
  • 144.2k
  • 22
  • 188
  • 473
Source Link

A Tour of Go, problem #56 - method implementation

New to Go, trying to see if the following error handling method can be further improved?

package main

import (
    "fmt"
    "math"
)

type ErrNegativeSqrt float64

func (e ErrNegativeSqrt) Error() string {
    return fmt.Sprintf("cannot Sqrt negative number: %f", float64(e))
}

func Sqrt(f float64) (float64, error) {
    if f > 0 {
        return math.Sqrt(f), nil
    } else {
        return 0, ErrNegativeSqrt(f)
    }
}

func main() {
    fmt.Println(Sqrt(2))
    fmt.Println(Sqrt(-2))
}