-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
60 lines (50 loc) · 1.24 KB
/
main.go
File metadata and controls
60 lines (50 loc) · 1.24 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
package main
import (
"fmt"
)
//TIP <p>To run your code, right-click the code and select <b>Run</b>.</p> <p>Alternatively, click
// the <icon src="AllIcons.Actions.Execute"/> icon in the gutter and select the <b>Run</b> menu item from here.</p>
func main() {
var x, y float64
var sign string
fmt.Println("Enter the first number: ")
fmt.Scan(&x)
fmt.Println("Enter operator (+, -, *, /): ")
fmt.Scan(&sign)
fmt.Println("Enter the second number: ")
fmt.Scan(&y)
cal := Draft[float64, float64]{
x, y, sign,
}
result, err := calculate(cal)
if err != nil {
fmt.Println(err)
} else {
fmt.Printf("## %.2f %s %.2f = %.2f\n", x, sign, y, result)
}
}
type Draft[F Number, S Number] struct {
firstNumb F
secondNumb S
operator string
}
type Number interface {
int | int64 | float32 | float64 | complex64 | complex128
}
func calculate(d Draft[float64, float64]) (float64, error) {
switch d.operator {
case "+":
return d.firstNumb + d.secondNumb, nil
case "-":
return d.firstNumb - d.secondNumb, nil
case "*":
return d.firstNumb * d.secondNumb, nil
case "/":
if d.secondNumb == 0 {
return 0, fmt.Errorf("you can't divide by 0")
}
return d.firstNumb / d.secondNumb, nil
default:
return 0, fmt.Errorf("invalid operator")
}
}