What panic is ?
Panic is a built-in function that stops the ordinary flow of control and begins panicking
package main
import (
"fmt"
)
func Div(num, divisor int) int {
return num/divisor
}
func main() {
a := 10
b := 0
fmt.Println(Div(a,b))
}
package main
import (
"fmt"
)
type Person struct {
Name string
Age int
}
func GetName(p *Person) string {
return p.Name
}
func main() {
fmt.Println(GetName(nil))
}
panic: runtime error: invalid memory address or nil pointer dereference
[signal SIGSEGV: segmentation violation code=0xffffffff addr=0x0 pc=0xc64da]
goroutine 1 [running]:
main.main()
/tmp/sandbox914181347/main.go:18 +0x1a
package main
import (
"fmt"
)
type Person struct {
Name string
Age int
}
func Div(p *Person, divisor int) int {
if divisor == 0 {
return 0
}
return p.Age/divisor
}
func main() {
p := &Person{}
p = nil
fmt.Println(Div(p,3))
}
package main
import (
"fmt"
)
type Person struct {
Name string
Age int
}
func Div(p *Person, divisor int) int {
return p.Age/divisor
}
func main() {
defer func() {
if r := recover(); r != nil {
fmt.Println("Recovered in f", r)
}
}()
p := &Person{}
p = nil
fmt.Println(Div(p,3))
}
Try Catch Taste on Golang
package main
import (
"log"
"fmt"
)
type Block struct {
Try func()
Catch func(Exception)
Finally func()
}
type Exception interface{}
func (b Block) Do() {
if b.Finally != nil {
defer b.Finally()
}
if b.Catch != nil {
defer func() {
if r := recover(); r != nil {
b.Catch(r)
}
}()
}
b.Try()
}
func main () {
res := 0
Block {
Try: func() {
a := 0
b := 1
res = b/a
},
Catch: func(e Exception) {
log.Println(e)
},
Finaly: func() {
fmt.Println("finished")
},
}.Do()
fmt.Println(res)
}
package main
import (
"fmt"
)
type Person struct {
name string
}
func (p Person) GetName() string {
return p.name
}
func main() {
p := Person{name:"hamdi"}
fmt.Println(p.GetName())
}
package main
import (
"fmt"
)
// public
func GetName() string {
return "hamdi"
}
// private
func updateName(s *string) {
s = "hamdi"
}
package main
import (
"fmt"
)
type Animal interface {
Walk() int
Talk() string
}
type Cow struct {
Leg int
Weight int
}
type Snake struct {
Poison bool
Tall int
}
func (c Cow) Walk() int {
return 1
}
func (s Snake) Walk() int {
return 3
}
func (s Snake) Talk() string {
return "Tsah"
}
func (c Cow) Talk() string {
return "Mooo"
}
func (c Cow) Run() int {
return "10"
}
package main
import (
"fmt"
)
type Animal interface {
Walk() int
Talk() string
}
type Cow struct {
Leg int
Weight int
}
type Snake struct {
Poison bool
Tall int
}
func GetAnimal(s string) Animal {
if s == "mamal" {
return Cow{}
}
return Snake{}
}
package main
import (
"fmt"
)
type Car struct {
}
func (c Car) GetMaxSpeed() int {
return 120
}
func (c Car) GetWheels() int {
return 4
}
type ContainerTruck struct {
Car
Type string
}
func (c ContainerTruck) GetWheels() {
return 6
}
type SportCar struct {
Car
Type string
}
func (s SportCar) GetMaxSpeed() int {
return 200
}