Dmitry Telenkov hai 1 mes
pai
achega
2279cb77c3
Modificáronse 1 ficheiros con 55 adicións e 5 borrados
  1. 55 5
      books/go_head_first/misc/func.go

+ 55 - 5
books/go_head_first/misc/func.go

@@ -1,16 +1,66 @@
 package main
 
 import (
+	"errors"
 	"fmt"
+	"log"
+	"math"
 )
 
-func paintNeeded(width float64, height float64) {
+func manyReturns() (int, bool, string) {
+	return 1, true, "hello"
+
+	// usage
+	// myInt, myBool, myString := manyReturns()
+}
+
+func floatParts(number float64) (integerPart int, fractionalPart float64) {
+	wholeNumber := math.Floor(number)
+	return int(wholeNumber), number - wholeNumber
+}
+
+func test_err() {
+	// err := errors.New("height can't be negative")
+	err := fmt.Errorf("a height of %0.2f is invalid", -2.3333)
+	fmt.Println(err)
+	log.Fatal(err)
+}
+
+func divide(dividend float64, divisor float64) (float64, error) {
+	if divisor == 0.0 {
+		return 0, errors.New("can't divide by 0")
+	}
+	return dividend / divisor, nil
+}
+
+func paintNeeded(width float64, height float64) (float64, error) {
+	if width < 0 {
+		return 0, fmt.Errorf("a width of %0.2f is invalid", width)
+	}
+	if height < 0 {
+		return 0, fmt.Errorf("a height of %0.2f id invalid", height)
+	}
 	area := width * height
-	fmt.Printf("%.2f liters needed\n", area/10.0)
+	return area / 10, nil
 }
 
 func main() {
-	paintNeeded(4.2, 3.0)
-	paintNeeded(5.2, 3.5)
-	paintNeeded(5.2, 3.3)
+	quotient, err := divide(5.6, 0.0)
+	if err != nil {
+		fmt.Println(err)
+	} else {
+		fmt.Printf("%0.2f\n", quotient)
+	}
+
+	/*
+	   var amount float64
+	   amount, err := paintNeeded(4.2, 3.0)
+
+	   	if err != nil {
+	   		log.Fatal(err)
+	   	} else {
+
+	   		fmt.Printf("%0.2f liters needed\n", amount)
+	   	}
+	*/
 }