GO store value froom LOOP - go

package main
import "fmt"
func main() {
var kata, kosong, kebalikan string
fmt.Print("Kata :")
fmt.Scan(&kata)
panjang := len(kata)
for i := panjang - 1; i >= 0; i-- {
kebalikan := kosong + fmt.Print(string(kata[i]))
}
if kata == kebalikan {
fmt.Println("\n", true)
} else {
fmt.Println("\n", false)
}
}
does anybody know how to store kosong + fmt.Print(string(kata[i])) to kebalikan ? just new in golang
the error is multiple-value fmt.Print() in single-value context

There are two problems with your code.
You need to use fmt.Sprint instead of fmt.Print in your case. The former returns a string, the latter prints it to stdout.
Do not use : in kebalikan := kosong + fmt.Print(string(kata[i])). You do not want to create a new local variable, instead modify the existing variable.
Here is the fixed code:
package main
import "fmt"
func main() {
var kata, kosong, kebalikan string
fmt.Print("Kata :")
fmt.Scan(&kata)
panjang := len(kata)
for i := panjang - 1; i >= 0; i-- {
kebalikan = kosong + fmt.Sprint(string(kata[i]))
}
if kata == kebalikan {
fmt.Println("\n", true)
} else {
fmt.Println("\n", false)
}
}

Related

how to using reflect to create parametric entity

package main
import (
"fmt"
"reflect"
)
type Aservice struct {
}
type Adata struct {
msg string
}
type Bdata struct {
more string
}
var amap map[string]interface{} = make(map[string]interface{}, 1024)
func (aser *Aservice) Bar(data *Adata) error {
return nil
}
func (aser *Aservice) Foo(data *Bdata) error {
return nil
}
func main() {
var ser *Aservice
typeOfService := reflect.TypeOf(ser)
valueOfService := reflect.ValueOf(ser)
for i := 0; i < valueOfService.NumMethod(); i++ {
nref := valueOfService.Method(i).Type().In(0)
fmt.Println("++", nref.Elem().Name())
amap[typeOfService.Method(i).Name] = nref
}
}
Currently "Adata" and "Bdata" can be printed correctly
But I don’t know how to store the empty structure pointers of "Adata" and "Bdata" in amap
No idea for the next step
I want to use Method(i).Name() in amap to store the parameters that need to be passed in for the Method
Based on the suggestions in comments :
package main
import (
"fmt"
"reflect"
)
type Aservice struct {
}
type Adata struct {
msg string
}
type Bdata struct {
more string
}
var amap = map[string]interface{}{}
func (aser *Aservice) Bar(data *Adata) error {
return nil
}
func (aser *Aservice) Foo(data *Bdata) error {
return nil
}
func main() {
var ser *Aservice
typeOfService := reflect.TypeOf(ser)
valueOfService := reflect.ValueOf(ser)
for i := 0; i < valueOfService.NumMethod(); i++ {
nref := valueOfService.Method(i).Type().In(0)
amap[typeOfService.Method(i).Name] = reflect.New(nref.Elem()).Interface()
}
for k, v := range amap {
fmt.Printf("%s %#v\n", k, v)
}
}
Output:
Bar &main.Adata{msg:""}
Foo &main.Bdata{more:""}

Simple encryption of a string

I want to encrypt a string with Go, my actual code is:
package main
import (
"fmt"
)
const key = "\xbd\xb2\x3d\xbc\x20\xe2\x8c\x98" //some random numbers here
func Encrypt(input string) (output string) {
for i := 0; i < len(input); i++ {
output += fmt.Sprintf("\\x%02x", input[i] ^ key[i % len(key)])
}
return output;
}
func Decrypt(input string) (output string) {
key := "\xbd\xb2\x3d\xbc\x20\xe2\x8c\x98"
for i := 0; i < len(input); i++ {
output += string(input[i] ^ key[i % len(key)])
}
return output;
}
func main() {
stringa := "password"
encrypted := Encrypt(stringa)
fmt.Println(encrypted)
fmt.Println(Decrypt(encrypted))
fmt.Println(stringa)
}
\xcd\xd3\x4e\xcf\x57\x8d\xfe\xfc
áE^O|?è«áE U|?ï_á?|?'üáE[U|?êû
password
Problem is after encrypt string, when I try to decrypt return different output. Where did I go wrong?
It looks like your goal is to xor the the bytes in a string with the bytes in a key. Here's one way to do it:
func xor(input string) string {
output := make([]byte, len(input))
for i := 0; i < len(input); i++ {
output[i] = input[i] ^ key[i%len(key)]
}
return string(output)
}
The Encrypt and Decrypt functions are the same:
func Encrypt(input string) string { return xor(input) }
func Decrypt(input string) string { return xor(input) }

Set fields using Reflection

I am struggling with some Go lang code for a few days. I have a golang function that would set all the common fields like createdBy, updatedBy, etc inside a struct. I have googled a lot and have come up with the following code.
package main
import (
"fmt"
"reflect"
"time"
"strings"
)
type User struct {
UserId string `json:"userId"`
ObjectType string `json:"objectType"`
CreationDate string `json:"creationDate"`
UpdationDate string `json:"updationDate"`
Version int `json:"version"`
}
func main() {
//fmt.Println("Hello, playground")
var user = User{}
var k = setCommonParam(&user )
var p = k.(*User)
fmt.Println(p.CreationDate)
var l = *p
fmt.Println(l.ObjectType)
fmt.Println(reflect.TypeOf(k))
fmt.Println(reflect.TypeOf(user))
}
func setCommonParam(obj interface{}) (interface{}) {
entityValue := reflect.ValueOf(obj).Elem()
entityType := entityValue.Type()
for i:=0; i<entityValue.NumField(); i++ {
typeField := entityType.Field(i)
vField := entityValue.Field(i)
if typeField.Name == "ObjectType" {
vField.SetString(strings.ToLower(reflect.TypeOf(obj).Elem().Name()))
} else if typeField.Name == "CreationDate" {
vField.SetString(time.Now().Format(time.RFC3339))
} else if typeField.Name == "UpdationDate" {
vField.SetString(time.Now().Format(time.RFC3339))
} else if typeField.Name == "CreatedBy" {
} else if typeField.Name == "UpdatedBy" {
} else if typeField.Name == "Version" {
}
}
return obj
}
Is there any way I can write the following in a single line?
var k = setCommonParam(&user )
var p = k.(*User)
var l = *p
and do something like this:
user = setCommonParam(user)
I am sorry but I am new to this. Thanks.
If your question is "how to condense these 3 lines into one?", then the answer is:
var l = *(setCommonParam(&user).(*User))

Golang convert list objects to string

I have two structs:
type A struct {
BankCode string `json:"bankCode"`
BankName string `json:"bankName"`
}
And:
type B struct {
A
extra string `json:" extra"`
}
And two slices:
listsA []A and listsB []B
I want to get bankCodes from listA and listB. bankcodes only contains bankcodes. It is a []string
It will be so easy as using two function.
func getBankCodes(data []A) []string {
res := make([]string, len(data))
for i := 0; i < len(data); i++ {
res[i] = data[i].BankCode
}
return res
}
func getBankCodes(data []B) []string {
res := make([]string, len(data))
for i := 0; i < len(data); i++ {
res[i] = data[i].BankCode
}
return res
}
How to use one common function ?
Well the clean solution would be to use an interface, since go doesn't support classic inheritance, so something like []parentclass can't work. Interfaces however can only describe functions not a common field, so you have to implement a Getter (essentially).
// GetBankCoder provides a function that gives the BankCode
type GetBankCoder interface {
getBankCode() string
}
// implement GetBankCoder for A (and indirectly for B)
func (a A) getBankCode() string {
return a.BankCode
}
and make your getBankCodes work on that interface type, notice the parameter of the function as well as the statement inside the loop:
func getBankCodes(data []GetBankCoder) []string { // <-- changed
res := make([]string, len(data))
for i := 0; i < len(data); i++ {
res[i] = data[i].getBankCode() // <-- changed
}
return res
}
There are other solutions where the function parameter is of interface{} type and then reflection is used to assure you can actually do .BankCode, but I don't like those, as they are not adding more clarity either.
... However, I couldn't get the golang playground to make this work correctly without putting it into a []GetBankCoder var first, before giving it to the function.
banks := make([]GetBankCoder, 0)
banks = append(banks, A{ BankCode: "ABC", BankName: "ABC Bank"})
getBankCodes(banks)
You may use one common function like so:
func BankCodes(data interface{}) []string {
if reflect.TypeOf(data).Kind() != reflect.Slice {
panic("err: data is not slice")
}
slice := reflect.Indirect(reflect.ValueOf(data))
res := make([]string, slice.Len())
for i := 0; i < slice.Len(); i++ {
a := slice.Index(i).Interface().(BankCoder)
res[i] = a.Bankcode()
}
return res
}
Code (try on The Go Playground):
package main
import (
"fmt"
"reflect"
)
func main() {
bs := []B{B{A{"BC1", "BN"}, "e"}, B{A{"BC2", "BN"}, "e"}}
strs := BankCodes(bs)
fmt.Println(strs)
as := []A{A{"AC1", "BN"}, A{"AC2", "BN"}}
strs2 := BankCodes(as)
fmt.Println(strs2)
}
func BankCodes(data interface{}) []string {
if reflect.TypeOf(data).Kind() != reflect.Slice {
panic("err: data is not slice")
}
slice := reflect.Indirect(reflect.ValueOf(data))
res := make([]string, slice.Len())
for i := 0; i < slice.Len(); i++ {
a := slice.Index(i).Interface().(BankCoder)
res[i] = a.Bankcode()
}
return res
}
type A struct {
BankCode string `json:"bankCode"`
BankName string `json:"bankName"`
}
type B struct {
A
extra string `json:" extra"`
}
type BankCoder interface {
Bankcode() string
}
func (a A) Bankcode() string {
return a.BankCode
}

How do I access struct fields that are part of a vector.Vector?

I am looking for help understanding how to access struct fields that are inside a container.vector.Vector.
The following code:
package main
import "fmt"
import "container/vector"
func main() {
type Hdr struct {
H string
}
type Blk struct {
B string
}
a := new(vector.Vector)
a.Push(Hdr{"Header_1"})
a.Push(Blk{"Block_1"})
for i := 0; i < a.Len(); i++ {
fmt.Printf("a.At(%d) == %+v\n", i, a.At(i))
x := a.At(i)
fmt.Printf("%+v\n", x.H)
}
}
Produces the error prog.go:22: x.H undefined (type interface { } has no field or method H)
removing lines 21 and 22 produces:
a.At(0) == {H:Header_1}
a.At(1) == {B:Block_1}
So, how exactly does one access 'H' or 'B'? It seems like I need to convert those interfaces to structs, but... I dunno. I'm at a loss.
Thanks for any help.
Use a Go type switch or type assertion to distinguish between the Hdr and Blk types. For example,
package main
import (
"fmt"
"container/vector"
)
func main() {
type Hdr struct {
H string
}
type Blk struct {
B string
}
a := new(vector.Vector)
a.Push(Hdr{"Header_1"})
a.Push(Blk{"Block_1"})
for i := 0; i < a.Len(); i++ {
fmt.Printf("a.At(%d) == %+v\n", i, a.At(i))
x := a.At(i)
switch x := x.(type) {
case Hdr:
fmt.Printf("%+v\n", x.H)
case Blk:
fmt.Printf("%+v\n", x.B)
}
}
}
However, effective the weekly.2011-10-18 release:
The container/vector package has been deleted. Slices are better:
SliceTricks.
Therefore, for the latest releases,
package main
import "fmt"
func main() {
type Hdr struct {
H string
}
type Blk struct {
B string
}
var a []interface{}
a = append(a, Hdr{"Header_1"})
a = append(a, Blk{"Block_1"})
for i := 0; i < len(a); i++ {
fmt.Printf("a[%d]) == %+v\n", i, a[i])
x := a[i]
switch x := x.(type) {
case Hdr:
fmt.Printf("%+v\n", x.H)
case Blk:
fmt.Printf("%+v\n", x.B)
}
}
}

Resources