Create struct in one function to be used in another - go

I am new to Golang and still trying to get my head around structs. I can't seem to figure out how to and create it in one function and use it in another.
Here is my code.
File 1 main.go
package main
import (
"github.com/asolopovas/docker_valet/modules"
"fmt"
)
func main {
fl := dockervalet.GetFlags()
fmt.Pringln(fl.user) // returns fl.user undefined
}
File 2 flags.go
package dockervalet
import (
"flag"
"fmt"
)
type Flags struct {
user string
}
func GetFlags() Flags {
var userFlag string
flag.StringVar(&userFlag, "u", "", "")
flag.StringVar(&userFlag, "user", "", "")
flag.Parse()
fl := Flags{
user: userFlag,
}
fmt.Println(fl.user) // works as expected
return fl
}
Thanks in advance.

Ok, I think I figured it out. The problem wash that I had to use First Capital letters to be able to access this return struct in another function.
File 1 main.go
func main {
fl := GetFlags()
fmt.Pringln(fl.User)
}
File 2 flags.go
type Flags struct {
User string
}
func GetFlags() Flags {
var userFlag string
flag.StringVar(&userFlag, "u", "", "")
flag.StringVar(&userFlag, "user", "", "")
flag.Parse()
fl := Flags{
User: userFlag,
}
fmt.Println(fl.user) // works as expected
return fl
}

Related

Unexpected newline in composite literal for a map[string]any

I'm new to Go and I try to build a Json-builder functionality to practice. My aim is to create a recursive library to build json.
This is the warning I get for the "second" field.
Unexpected newline in composite literal
and here's my attempt. I don't see a mistake here:
package main
import (
"fmt"
)
type JsonNode struct{
fields map[string]interface{}
}
func BuildJson (fields) JsonNode {
jn := &JsonNode{}
for key,value := range fields {
jn.fields[key] = value
}
return jn
}
func main () {
json := BuildJson(
map[string]any{
"first": 1,
"second": BuildJson(map[string]any{"child": "test"}) // Error for this line.
}
)
fmt.Printf(json)
}
You have multiple errors in your code. This version works, I suggest you use some IDE that report errors prior to compilation (they sometimes fix it for you).
package main
import (
"fmt"
)
type JsonNode struct {
fields map[string]interface{}
}
func BuildJson(fields map[string]any) JsonNode {
jn := &JsonNode{}
jn.fields = make(map[string]interface{})
for key, value := range fields {
jn.fields[key] = value
}
return *jn
}
func main() {
json := BuildJson(
map[string]any{
"first": 1,
"second": BuildJson(map[string]any{"child": "test"}), // Error for this line.
},
)
fmt.Println(json)
}
playground

How to create a variable of dynamic type

I am able to create a variable 'model' of type 'Sample' as follows:
type Sample struct {
Id int `jsonapi:"attr,id,omitempty"`
Name string `jsonapi:"attr,name,omitempty"`
}
var model Sample // created successfully
I am able to create it successfully as I already know the struct type (Sample).
However, when I tried to create a similar variable 'a' as follows, I get syntax error:
package main
import (
"fmt"
"reflect"
)
type Sample struct {
Id int `jsonapi:"attr,id,omitempty"`
Name string `jsonapi:"attr,name,omitempty"`
}
func test(m interface{}) {
fmt.Println(reflect.TypeOf(m)) // prints 'main.Sample'
var a reflect.TypeOf(m) // it throws - syntax error: unexpected ( at end of statement
}
func main() {
var model Sample // I have created a model of type Sample
model = Sample{Id: 1, Name: "MAK"}
test(model)
}
Please advise how to create a variable of dynamic type in Go.
package main
import (
"fmt"
"reflect"
)
type Sample struct {
Id int `jsonapi:"attr,id,omitempty"`
Name string `jsonapi:"attr,name,omitempty"`
}
func test(m interface{}) {
fmt.Println(reflect.TypeOf(m)) // prints 'main.Sample'
a, ok := m.(main.Sample)
if ok {
fmt.Println(a.Id)
}
}
func main() {
var model Sample // I have created a model of type Sample
model = Sample{Id: 1, Name: "MAK"}
test(model)
}
and if you want a little more dynamism, you can use a type switch. Instead of the a, ok := m.(main.Sample), you do
switch a := m.(type) {
case main.Sample:
fmt.Println("It's a %s", reflect.TypeOf(m))
case default:
fmt.Println("It's an unknown type")
}

Can anyone help to parse HCL?

I'm going to parse HCL configuration file using this repository.
package main
import (
"fmt"
hclParser "github.com/hashicorp/hcl/hcl/parser"
)
const (
EXAMPLE_CONFIG_STRING = "log_dir = \"/var/log\""
)
func main() {
// parse HCL configuration
if astFile, err := hclParser.Parse([]byte(EXAMPLE_CONFIG_STRING)); err == nil {
fmt.Println(astFile)
} else {
fmt.Println("Parsing failed.")
}
}
How can I parse log_dir in this case?
github.com/hashicorp/hcl/hcl/parser is a low-level package. Use the high-level API instead:
package main
import (
"fmt"
"github.com/hashicorp/hcl"
)
type T struct {
LogDir string `hcl:"log_dir"`
}
func main() {
var t T
err := hcl.Decode(&t, `log_dir = "/var/log"`)
fmt.Println(t.LogDir, err)
}
There is also DecodeObject available if you really want to deal with the AST yourself.

Go fmt.Println display wrong contain

I am studying GO by using "a tour of go"
The code is doing very simple things, combine first and last together and output on screen.
The output is a hex address instead of "aaabbb" after I run the code. Could anyone can help me out? Thank you
package main
import "fmt"
type Name struct{
first,last string
}
func (name Name) fullName() string{
return (name.first + name.last)
}
func main(){
v := Name{"aaa","bbb"}
fmt.Println(v.fullName)
}
You are not calling the function fullName. you are just passing 'the pointer' to it:
see this http://play.golang.org/p/GjibbfoyH0
package main
import "fmt"
type Name struct {
first, last string
}
func (name Name) fullName() string {
return (name.first + name.last)
}
func main() {
v := Name{"aaa", "bbb"}
fmt.Println(v.fullName())
}
Use the result of the method
fmt.Println(v.fullName())
not the address of the method
fmt.Println(v.fullName)
For example,
package main
import "fmt"
type Name struct{
first,last string
}
func (name Name) fullName() string{
return (name.first + name.last)
}
func main(){
v := Name{"aaa","bbb"}
fmt.Println(v.fullName())
}
Output:
aaabbb

Flag command line parsing in golang

I'm not sure I understand the reasoning behind this example (taken from here), nor what it is trying to communicate about the Go language:
package main
import (
"flag"
"fmt"
)
func main() {
f := flag.NewFlagSet("flag", flag.ExitOnError)
f.Bool("bool", false, "this is bool flag")
f.Int("int", 0, "this is int flag")
visitor := func(a *flag.Flag) {
fmt.Println(">", a.Name, "value=", a.Value)
}
fmt.Println("Visit()")
f.Visit(visitor)
fmt.Println("VisitAll()")
f.VisitAll(visitor)
// set flags
f.Parse([]string{"-bool", "-int", "100"})
fmt.Println("Visit() after Parse()")
f.Visit(visitor)
fmt.Println("VisitAll() after Parse()")
f.VisitAll(visitor)
}
Something along the lines of the setup they have but then adding a
int_val := f.get("int")
to get the named argument would seem more useful. I'm completely new to Go, so just trying to get acquainted with the language.
This is complicated example of using flag package. Typically flags set up this way:
package main
import "flag"
// note, that variables are pointers
var strFlag = flag.String("long-string", "", "Description")
var boolFlag = flag.Bool("bool", false, "Description of flag")
func init() {
// example with short version for long flag
flag.StringVar(strFlag, "s", "", "Description")
}
func main() {
flag.Parse()
println(*strFlag, *boolFlag)
}

Resources