Data commit
This commit is contained in:
parent
7387c8f97b
commit
cb5bb5e222
199093 changed files with 3378972 additions and 0 deletions
1
Task/Generic-swap/Go/generic-swap-1.go
Normal file
1
Task/Generic-swap/Go/generic-swap-1.go
Normal file
|
|
@ -0,0 +1 @@
|
|||
a, b = b, a
|
||||
14
Task/Generic-swap/Go/generic-swap-2.go
Normal file
14
Task/Generic-swap/Go/generic-swap-2.go
Normal file
|
|
@ -0,0 +1,14 @@
|
|||
package main
|
||||
|
||||
import "fmt"
|
||||
|
||||
func swap(a, b *interface{}) {
|
||||
*a, *b = *b, *a
|
||||
}
|
||||
|
||||
func main() {
|
||||
var a, b interface{} = 3, "four"
|
||||
fmt.Println(a, b)
|
||||
swap(&a, &b)
|
||||
fmt.Println(a, b)
|
||||
}
|
||||
51
Task/Generic-swap/Go/generic-swap-3.go
Normal file
51
Task/Generic-swap/Go/generic-swap-3.go
Normal file
|
|
@ -0,0 +1,51 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"reflect"
|
||||
)
|
||||
|
||||
func swap(a, b interface{}) error {
|
||||
ta := reflect.TypeOf(a)
|
||||
tb := reflect.TypeOf(b)
|
||||
if ta != tb {
|
||||
return fmt.Errorf("swap args are different types: %v and %v", ta, tb)
|
||||
}
|
||||
if ta.Kind() != reflect.Ptr {
|
||||
return fmt.Errorf("swap args must be pointers")
|
||||
}
|
||||
ea := reflect.ValueOf(a).Elem()
|
||||
eb := reflect.ValueOf(b).Elem()
|
||||
temp := reflect.New(ea.Type()).Elem()
|
||||
temp.Set(ea)
|
||||
ea.Set(eb)
|
||||
eb.Set(temp)
|
||||
return nil
|
||||
}
|
||||
|
||||
func main() {
|
||||
a, b := 3, "cats"
|
||||
fmt.Println("a b:", a, b)
|
||||
err := swap(a, b)
|
||||
fmt.Println(err, "\n")
|
||||
|
||||
c, d := 3, 4
|
||||
fmt.Println("c d:", c, d)
|
||||
err = swap(c, d)
|
||||
fmt.Println(err, "\n")
|
||||
|
||||
e, f := 3, 4
|
||||
fmt.Println("e f:", e, f)
|
||||
swap(&e, &f)
|
||||
fmt.Println("e f:", e, f, "\n")
|
||||
|
||||
type mult struct {
|
||||
int
|
||||
string
|
||||
}
|
||||
|
||||
g, h := mult{3, "cats"}, mult{4, "dogs"}
|
||||
fmt.Println("g h:", g, h)
|
||||
swap(&g, &h)
|
||||
fmt.Println("g h:", g, h)
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue