Organized code and improved error handling

Added really primitive error handling to numStar scanning, I really have
to figure out how to properly handle errors in Golang beyond abusing
if/else and switch/case
This commit is contained in:
raul 2024-01-20 12:23:39 +01:00
parent c33ebb25f0
commit e56ec312f6
3 changed files with 58 additions and 32 deletions

3
star-shapes/go.mod Normal file
View File

@ -0,0 +1,3 @@
module star-shapes
go 1.21.6

View File

@ -11,11 +11,28 @@ func main() {
var numShape int var numShape int
// TODO: Add error handling for star number // TODO: Add error handling for star number
fmt.Println("How many stars do you want?") forStars:
fmt.Printf(" Stars: ") for {
fmt.Scan(&numStar)
fmt.Printf("\n") fmt.Println("How many stars do you want?")
fmt.Printf(" Stars: ")
fmt.Scan(&numStar)
// This is confusing
// switch v := interface{}(numStar).(type) {
// case int:
// break forStars
// default:
// fmt.Printf("ERROR, %v is invalid input", v)
// panic("ERROR")
// }
if numStar >= 0 {
break forStars
} else {
fmt.Printf("\n[-] INVALID NUMBER\n\n")
}
}
forShapes: forShapes:
for { for {
@ -38,31 +55,3 @@ forShapes:
} }
} }
} }
func line(num int) {
for i := 0; i < num; i++ {
fmt.Printf("* ")
}
fmt.Printf("\n")
}
func square(num int) {
for i := 0; i < num; i++ {
for i := 0; i < num; i++ {
fmt.Printf("* ")
}
fmt.Printf("\n")
}
}
func flag(num int) {
for a := 0; a < num; a++ {
for i := -1; i < a; i++ {
fmt.Printf("* ")
}
fmt.Printf("\n")
}
for i := 0; i < num/2; i++ {
println("*")
}
}

34
star-shapes/shapes.go Normal file
View File

@ -0,0 +1,34 @@
package main
import "fmt"
// Drawing a line of asterisks
func line(num int) {
for i := 0; i < num; i++ {
fmt.Printf("* ")
}
fmt.Printf("\n")
}
// Drawing a square of asterisks
func square(num int) {
for i := 0; i < num; i++ {
for i := 0; i < num; i++ {
fmt.Printf("* ")
}
fmt.Printf("\n")
}
}
// Drawing a flag of asterisks
func flag(num int) {
for a := 0; a < num; a++ {
for i := -1; i < a; i++ {
fmt.Printf("* ")
}
fmt.Printf("\n")
}
for i := 0; i < num/2; i++ {
println("*")
}
}