swap two strings (Golang) - go

I am currently learning Golang, and i decided to write few simple algorithm for learning the syntax. i hope it's not already answers but i didn't found it ..
I have a problem for swapping string
func swap(str1, str2 string) {
/*
* Also possible :
* str1, str2 = str2, str1
*/
// str1, str2 = str2, str1
tmp := str1
str1 = str2
str2 = tmp
}
func main() {
a := "World !"
b := "Hello"
swap(a, b)
fmt.Printf("a=%s\nb=%s\n", a, b)
}
Why this code didn't work ?

Swapping str1 and str2 doesn't change a and b, because they are copies of a and b. Use pointers:
func swap(str1, str2 *string) {
*str1, *str2 = *str2, *str1
}
func main() {
a := "salut"
b := "les gens"
swap(&a, &b)
fmt.Printf("a=%s\nb=%s\n", a, b)
}
http://play.golang.org/p/Qw0t5I-XGT

This will be the idiomatic way.
package main
import "fmt"
func swap(a, b string)(string, string) {
return b, a
}
func main() {
f, s := swap("world" , "hello")
fmt.Println(f, s)
}

Built-in types as function arguments are passed by value, but if the elements for dereference will modify the original value, such as slice, map. e.g.
package main
import (
"bytes"
"fmt"
"strings"
)
func f_1(a int) {
a = 2
}
func f_1_1(a *int) {
*a = 2
}
func f_2(s string) {
s = "cba"
}
func f_2_1(s *string) {
*s = "cba"
}
func f_3(v []string) {
v[0] = "haha"
}
func f_3_1(v []string) {
v = nil
}
func f_3_2(v *[]string) {
*v = nil
}
func f_4(m map[int]int) {
m[1] = 3
m[3] = 1
}
func f_4_1(m map[int]int) {
m = nil
}
func f_4_2(m *map[int]int) {
*m = nil
}
func f_5(b []byte) {
b[0] = 0x40
}
func f_5_1(b []byte) {
b = bytes.Replace(b, []byte("1"), []byte("a"), -1)
}
func f_5_2(b *[]byte) {
*b = bytes.Replace(*b, []byte("1"), []byte("a"), -1)
}
type why struct {
s []string
}
func (ss why) SetV(s []string) {
ss.s = s
}
func (ss *why) SetP(s []string) {
ss.s = s
}
func (ss why) String() string {
return strings.Join(ss.s, ",")
}
func main() {
a := 1
s := "abc"
v := []string{"sd", "aa"}
m := map[int]int{1: 1, 2: 2, 3: 3}
f_1(a)
f_2(s)
f_3(v)
f_4(m)
fmt.Printf("%d,%s,%v,%v\n", a, s, v, m)
f_3_1(v)
f_4_1(m)
fmt.Printf("%d,%s,%v,%v\n", a, s, v, m)
f_1_1(&a)
f_2_1(&s)
f_3_2(&v)
f_4_2(&m)
fmt.Printf("%d,%s,%v,%v\n", a, s, v, m)
b := []byte("12145178")
f_5(b)
fmt.Printf("%s\n", b)
f_5_1(b)
fmt.Printf("%s\n", b)
f_5_2(&b)
fmt.Printf("%s\n", b)
ss := &why{}
ss.SetV([]string{"abc", "efg"})
fmt.Println(ss)
ss.SetP([]string{"abc", "efg"})
fmt.Println(ss)
}

you can write as that:
a := "hello"
b := "world"
a, b = b, a

package main
import "fmt"
func swap(a,b string)(string, string){
return b,a
}
func main(){
fmt.Println(swap("Lang","Go"))
}

Related

How to convert a slice of int to a slice of string

Well, I created a slice of int like this:
list_of_id := []string {1,2,3,4}
My code would do a check if a variable in my slice (list_of_id):
func contains(s [] int, input int) bool {
for _, v := range s {
if v == input {
return true
}
}
return false
}
func main() {
list_of_id := [] int {1,2,3,4}
fmt.Println(contains(list_of_id, 1))
}
I want to create a function with the flexibility that I could input 1 or "1" as well.
My intention is to create an if else condition in which the slice of int [] int {1,2,3,4} will be converted into a slice of string [] string {"1","2","3","4"} to check again.
Anddddd, I don't know how to do so. I tried to google it out but all I found is a solution to convert this [] int {1,2,3,4} to this "{1,2,3,4}"
import "strconv"
func contains(s [] int, input interface{}) bool {
switch i := input.(type) {
case int:
for _, v := range s {
if v == i {
return true
}
}
case string:
for _, v := range s {
if strconv.Itoa(v) == i {
return true
}
}
}
return false
}
https://play.golang.org/p/02J1f77n_aM
package main
import (
"fmt"
"strconv"
)
func contains(s []int, input interface{}) bool {
var c int
var err error
switch input.(type) {
case int:
c = input.(int)
case string:
tmp := input.(string)
c, err = strconv.Atoi(tmp)
}
if err != nil {
return false
}
for _, v := range s {
if v == c {
return true
}
}
return false
}
func main() {
list_of_id := []int{1, 2, 3, 4}
fmt.Println(contains(list_of_id, 3))
fmt.Println(contains(list_of_id, 5))
fmt.Println(contains(list_of_id, "1"))
fmt.Println(contains(list_of_id, "6"))
}
Here example

How do I compare equality of function types?

I am doing some testing and trying to test for equality of some function types. I have https://play.golang.org/p/GeE_YJF5lz :
package main
import (
"fmt"
"reflect"
)
type myStruct struct {
f []someFunc
}
type someFunc func(a string) bool
var sf1 someFunc = func(a string) bool {
return true
}
var sf2 someFunc = func(a string) bool {
return false
}
func main() {
a := []someFunc{sf1, sf2}
b := []someFunc{sf1, sf2}
fmt.Println(reflect.DeepEqual(a, b)) // false
m := &myStruct{
f: []someFunc{sf1, sf2},
}
n := &myStruct{
f: []someFunc{sf1, sf2},
}
fmt.Println(reflect.DeepEqual(m, n)) // false
}
I haven't been able to find anything in the docs about comparing functions and know I must be missing something important as to why reflect.DeepEqual doesn't work for them properly.
You can compare function like this, Read more about the representation of functions here: http://golang.org/s/go11func
func funcEqual(a, b interface{}) bool {
av := reflect.ValueOf(&a).Elem()
bv := reflect.ValueOf(&b).Elem()
return av.InterfaceData() == bv.InterfaceData()
}
For example: This is just an idea for your start point.
func main() {
a := []someFunc{sf1, sf2}
b := []someFunc{sf1, sf2}
for idx, f := range a {
fmt.Println("Index: ", idx, funcEqual(f, b[idx]))
}
}
Output:
Index: 0 true
Index: 1 true
Play link: https://play.golang.org/p/6cSVXSYfa5

How can I compare struct data and interface data in Golang?

I am trying to create a generic Binary Tree in Golang. How can I compare data from an interface and input data in the code? Here is an example of what I am trying to do. The comparison that is giving me trouble is this
} else if cur.data < data {
-
package DSAA
type TreeNode struct {
data interface{}
right *TreeNode
left *TreeNode
}
type BinarySearchTree struct {
root *TreeNode
}
func BSTCreate() *BinarySearchTree {
return &BinarySearchTree{nil}
}
func (b *BinarySearchTree) Insert(cur TreeNode, data interface{}) *BinarySearchTree {
if &cur == nil {
cur := &TreeNode{data, nil, nil}
} else if cur.data < data {
b = b.Insert(*cur.left, data)
} else {
b = b.Insert(*cur.right, data)
}
return b
}
You have some options:
1- Using runtime type switch:
package main
import (
"fmt"
)
func main() {
fmt.Println(Less(1, 2)) // true
fmt.Println(Less("AB", "AC")) // true
}
func Less(a, b interface{}) bool {
switch v := a.(type) {
case int:
w := b.(int)
return v < w
case string:
w := b.(string)
return v < w
}
return false
}
then replace } else if cur.data < data { with
} else if Less(cur.data , data) {
2- Using Comparer interface:
package main
import (
"fmt"
)
type Comparer interface {
// Less reports whether the element is less than b
Less(b interface{}) bool
}
func main() {
a, b := Int(1), Int(2)
fmt.Println(a.Less(b)) // true
c, d := St("A"), St("B")
fmt.Println(c.Less(d)) // true
}
type Int int
func (t Int) Less(b interface{}) bool {
if v, ok := b.(Int); ok {
return int(t) < int(v)
}
return false
}
type St string
func (t St) Less(b interface{}) bool {
if v, ok := b.(St); ok {
return string(t) < string(v)
}
return false
}
3- Using reflect

How do you create a slice of functions with different signatures?

How do you create a slice of functions with different signatures? I tried the code below but its feels hack-ish. Do we just bite the bullet and use a slice interface{}?
package main
import (
"fmt"
)
type OneParams func(string) string
type TwoParams func(string, string) string
type ThreeParams func(string, string, string) string
func (o OneParams) Union() string {
return "Single string"
}
func (t TwoParams) Union() string {
return "Double string"
}
func (t ThreeParams) Union() string {
return "Triple string"
}
type Functions interface {
Union() string
}
func Single(str string) string {
return str
}
func Double(str1 string, str2 string) string {
return str1 + " " + str2
}
func Triple(str1 string, str2 string, str3 string) string {
return str1 + " " + str2 + " " + str3
}
func main() {
fmt.Println("Slice Of Functions Program!\n\n")
fSlice := []Functions{
OneParams(Single),
TwoParams(Double),
ThreeParams(Triple),
}
for _, value := range fSlice {
switch t := value.(type) {
case OneParams:
fmt.Printf("One: %s\n", t("one"))
case TwoParams:
fmt.Printf("Two: %s\n", t("one", "two"))
case ThreeParams:
fmt.Printf("Three: %s\n", t("one", "two", "three"))
default:
fmt.Println("Huh! What's that?")
}
}
fmt.Println("\n\n")
}
Is this just a case of trying to do too much with Go?
Please check it, I don't know if it what you want. Because I don't know what are you exactly want.
package main
import (
"fmt"
"reflect"
)
func A() {
fmt.Println("A")
}
func B(A int) {
fmt.Println("B", A)
}
func C(A string, B float32) {
fmt.Println("C", A, B)
}
func main() {
f := []interface{}{A, B, C}
f[0].(func())()
f[1].(func(int))(15)
f[2].(func(string, float32))("TEST", 90)
fmt.Println("\n******* another thing ******")
for a, v := range f {
v := reflect.TypeOf(v)
fmt.Println("#######", a)
fmt.Println("num param :", v.NumIn())
for i := 0; i < v.NumIn(); i++ {
fmt.Println("param :", i, "type is ", v.In(i))
}
}
}
Check on Go Playground
Here I have another example calling using reflect
package main
import (
"fmt"
"reflect"
)
func A() {
fmt.Println("A")
}
func B(A int) {
fmt.Println("B", A)
}
func C(A string, B float32) {
fmt.Println("C", A, B)
}
func main() {
f := []interface{}{A, B, C}
f[0].(func())()
f[1].(func(int))(15)
f[2].(func(string, float32))("TEST", 90)
fmt.Println("\n******* calling with reflect ******")
for a, v := range f {
v := reflect.TypeOf(v)
//calling the function from reflect
val := reflect.ValueOf(f[a])
params := make([]reflect.Value, v.NumIn())
if v.NumIn() == 1 {
params[0] = reflect.ValueOf(1564)
} else if v.NumIn() == 2 {
params[0] = reflect.ValueOf("Test FROM reflect")
params[1] = reflect.ValueOf(float32(123456))
}
val.Call(params)
}
}
Check on Go Playground
depends on what the different you need. upon your example, we could use variadic.
package main
import(
"fmt"
"strings"
)
func foo(ss ...string) string{
return strings.Join(ss, " ")
}
func main(){
fmt.Println(foo("one"))
fmt.Println(foo("one", "two"))
fmt.Println(foo("one", "two", "three"))
}

ToString() function in Go

The strings.Join function takes slices of strings only:
s := []string{"foo", "bar", "baz"}
fmt.Println(strings.Join(s, ", "))
But it would be nice to be able to pass arbitrary objects which implement a ToString() function.
type ToStringConverter interface {
ToString() string
}
Is there something like this in Go or do I have to decorate existing types like int with ToString methods and write a wrapper around strings.Join?
func Join(a []ToStringConverter, sep string) string
Attach a String() string method to any named type and enjoy any custom "ToString" functionality:
package main
import "fmt"
type bin int
func (b bin) String() string {
return fmt.Sprintf("%b", b)
}
func main() {
fmt.Println(bin(42))
}
Playground: http://play.golang.org/p/Azql7_pDAA
Output
101010
When you have own struct, you could have own convert-to-string function.
package main
import (
"fmt"
)
type Color struct {
Red int `json:"red"`
Green int `json:"green"`
Blue int `json:"blue"`
}
func (c Color) String() string {
return fmt.Sprintf("[%d, %d, %d]", c.Red, c.Green, c.Blue)
}
func main() {
c := Color{Red: 123, Green: 11, Blue: 34}
fmt.Println(c) //[123, 11, 34]
}
Another example with a struct :
package types
import "fmt"
type MyType struct {
Id int
Name string
}
func (t MyType) String() string {
return fmt.Sprintf(
"[%d : %s]",
t.Id,
t.Name)
}
Be careful when using it,
concatenation with '+' doesn't compile :
t := types.MyType{ 12, "Blabla" }
fmt.Println(t) // OK
fmt.Printf("t : %s \n", t) // OK
//fmt.Println("t : " + t) // Compiler error !!!
fmt.Println("t : " + t.String()) // OK if calling the function explicitly
This works well
package main
import "fmt"
type Person struct {
fname, sname string
address string
}
func (p *Person) String() string {
s:= fmt.Sprintf("\n %s %s lives at %s \n", p.fname, p.sname, p.address)
return s
}
func main(){
alex := &Person{"Alex", "Smith", "33 McArthur Bvd"}
fmt.Println(alex)
}
Output:
Alex Smith lives at 33 McArthur Bvd
If you have a fixed set of possible types for elements that could be converted, then you can define conversion functions for each, and a general conversion function that uses reflection to test the actual type of an element and call the relevant function for that element, eg:
func ToStringint(x int) string {
return strconv.Itoa(x)
}
func ToStringlong(x int64) string {
return strconv.FormatInt(x,10)
}
func ToStringdouble(x float64) string {
return fmt.Sprintf("%f", x)
}
func ToStringboolean(x bool) string {
if x {
return "true"
}
return "false"
}
func ToStringOclAny(x interface{}) string {
if reflect.TypeOf(x) == TYPEint {
return strconv.Itoa(x.(int))
}
if reflect.TypeOf(x) == TYPEdouble {
return fmt.Sprintf("%f", x.(float64))
}
if reflect.TypeOf(x) == TYPElong {
return strconv.FormatInt(x.(int64),10)
}
if reflect.TypeOf(x) == TYPEString {
return x.(string)
}
if reflect.TypeOf(x) == TYPEboolean {
return ToStringboolean(x.(bool))
}
if reflect.TypeOf(x) == TYPESequence {
return ToStringSequence(x.(*list.List))
}
if reflect.TypeOf(x) == TYPEMap {
return ToStringMap(x.(map[interface{}]interface{}))
}
return ""
}
func ToStringSequence(col *list.List) string {
res := "Sequence{"
for e := col.Front(); e != nil; e = e.Next() {
res = res + ToStringOclAny(e.Value)
if e.Next() != nil {
res = res + ", "
}
}
return res + "}"
}
func ToStringSet(col *list.List) string {
res := "Set{"
for e := col.Front(); e != nil; e = e.Next() {
res = res + ToStringOclAny(e.Value)
if e.Next() != nil {
res = res + ", "
}
}
return res + "}"
}
func ToStringMap(m map[interface{}]interface{}) string {
res := "Map{"
for i, v := range m {
res = res + ToStringOclAny(i) + " |-> " + ToStringOclAny(v) + " "
}
return res + "}"
}
Here is a simple way to handle this:
package main
import (
"fat"
"strconv"
)
type Person struct {
firstName, lastName string
age int
}
func (p Person) GetFullName() string {
return p.firstName + " " + p.lastName
}
func (p Person) GetAge() int {
return p.age
}
func (p Person) GetAgeAsString() string {
return strconv.Itoa(p.age)
}
func main() {
p := Person {"John", "Doe", 21}
fmt.Println(p.GetFullName())
fmt.Println(p.GetAgeAsString())
}
Output:
"John Doe"
"21"
I prefer something like the following:
type StringRef []byte
func (s StringRef) String() string {
return string(s[:])
}
…
// rather silly example, but ...
fmt.Printf("foo=%s\n",StringRef("bar"))

Resources