Golang slice of structs

Continue

Golang slice of structs

It's not uncommon for public JSON APIs to reply with top level arrays, instead of a full JSON object. If you want to convert that JSON array into a slice of structs with the items of the array, heres how you can do it: package main import "fmt" import "encoding/json" type PublicKey struct { Id int Key string } type KeysResponse struct { Collection []PublicKey } func main() { keysBody := []byte(`[{"id": 1,"key": "-"},{"id": 2,"key": "-"},{"id": 3,"key": "-"}]`) keys := make([]PublicKey,0) json.Unmarshal(keysBody, &keys) fmt.Printf("%#v", keys) } Same code in the playground: Golang is not a very complicated language but has very poor documentation standards compared to more popular things, like Ruby or JS. I actually had to figure this out over ours of googling to find the answer here (in a code review from golang source!): Hope it helps. Instantly share code, notes, and snippets. Convert an interface{} containing a slice of structs to [][]string (used in CSV serialization) [golang reflection example] Runnable example here: You can't perform that action at this time. You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. Structs are a way to structure and use data. It allows us to group data. In this article, we will see how to declare and use it. Defining a Struct in Go To use a struct we declare the type of struct we are going to use. The code below shows how to define a struct type using the type keyword. package main import ( "fmt" ) type Fruit struct { name string } // to define a struct type use // type structname struct { // field1 type1 // field2 type2 // ... // } func main() { } Declaring Struct Variables We will see how to declare a struct variable. It is really simple as shown below. var variablename structname // declare a struct variable What is a zero-value Struct? When a struct is declared but has not assigned any value, it is then a zero-valued struct. That means, all the fields will take their respective zero-values from their types. package main import ( "fmt" ) type Fruit struct { name string } func main() { var apple Fruit fmt.Println(apple) // prints {} } Creating and initializing a Struct in GoLang Now, we will create structs and initialize them with values. There are a few ways we could do that. 1. Using struct Literal Syntax Struct literal syntax is just assigning values when declaring and it is really easy. package main import ( "fmt" ) type Fruit struct { name string } func main() { var apple = Fruit{"Apple"} // struct literal syntax fmt.Println(apple) // prints {Apple} } 2. Using the new keyword We can use the new keyword when declaring a struct. Then we can assign values using dot notation to initialize it. package main import ( "fmt" ) type Fruit struct { name string } func main() { var banana = new(Fruit) banana.name = "Banana" fmt.Println(banana) // prints &{Banana} } 3. Using pointer address operator The pointer address operator(&) can be used to declare a struct. Let's see how we would do that. package main import ( "fmt" ) type Fruit struct { name string } func main() { var mango = &Fruit{"Mango"} fmt.Println(mango) // prints &{Mango} } Types of Structs in Go A struct can both be named as well as unnamed or anonymous. Both have their uses. We will what are those and how to use them. 1. Named struct A named struct is any struct whose name has been declared before. So, it can be initialized using its name. type Food struct {} // Food is the name 2. Anonymous struct Now we will see the anonymous structs. They come in very handy. We will see how we create and use them. package main import ( "fmt" ) func main() { pizza := struct { name string }{ name: "Pizza", } fmt.Println(pizza) // prints {Pizza} } Fields of a Struct Object Structs have fields. It can be named or unnamed. They can be assigned values or can remain empty and thus have zero-value. Let's see how to initialize and use them. 1. Named fields in a struct Named fields are those whose name has been declared in the struct type declaration. Below is an example. type Food struct { name string // this field has name quantity int // ... } 2. Anonymous fields in a struct Anonymous fields are those whose type is declared only. In the example, we can see that any type can be used inside the struct. But this can create ambiguity and may result in a problem as you will see in the code. package main import ( "fmt" ) // none of the fields are named // these are anonymous fields // Throws error because of ambiguity // There are two string fields to choose from // p.string makes no sense to the compiler // type Painting struct { // string // painting's name // string // artist's name // } type Painting struct { string // painting name Artist // artist } type Artist struct { string } func main() { var p Painting p.string = "Starry Night" // p.string = "Van Gogh" // it will throw an error // "ambiguous selector p.string" p.Artist.string = "Van Gogh" fmt.Println(p) // prints {Starry Night {Van Gogh}} } 3. Functions as a field Structs can have functions as their field. Below is the code showing the usage of function inside a struct. import ( "fmt" ) // declare function type type FoodNameGetter func(string) string type Food struct { name string getter FoodNameGetter // declare function } func main() { pizza := Food{ name: "Pizza", getter: func(name string) string { // declare function body return "This is " + name + "." }, } fmt.Println(pizza.getter(pizza.name)) // prints "This is Pizza." } Accessing fields of a Struct Accessing fields of the struct are really simple. We use the dot operator for that. When a nested structure is there we use dot inside the nested struct as well. // declaration type Car struct { name string cost int } var c Car = Car{"Mercedes", 3500000} // accessing carMake := c.name carPrice := c.cost Now, for a nested struct, we can do like this: package main import ( "fmt" ) type User struct { name string } type Service struct { name string user User } func main() { google := Service{ name: "Google", user: User{ name: "John Doe", }, } // accessing from nested struct fmt.Println(google.user.name) // prints "John Doe" } Promoted fields When we use an anonymous struct inside another struct, all the fields from the anonymous struct becomes accessible from the outer struct as if it is a part of it. These fields are called promoted fields. package main import ( "fmt" ) type Person struct { name string } type StoreKeeper struct { Person } func main() { var p = StoreKeeper{} p.Person = Person{"Jane Doe"} // access the field as normal field fmt.Println(p.name) // prints "Jane Doe" } Using pointers of struct We can create pointers of a struct using the address-of operator(&). Here is an example showing just that. package main import ( "fmt" ) type Student struct { name string } func main() { ptrStudent := &Student{name: "John"} fmt.Println(ptrStudent) // prints &{John} } We can use new() function to get a pointer of that struct. Comparing Structs The structs can be compared if they have the same values in the same fields. Here is an example. package main import ( "fmt" ) type Student struct { name string } func main() { s1 := Student{"John"} s2 := Student{"John"} if(s1 == s2) { fmt.Println("They are equal") } else { fmt.Println("They are not equal") } // output: "They are equal" } Array of Structs Now we will see how to use structs in arrays. It is pretty simple and straightforward. 1. Declaring and initializing an Array of Structs We simply declare an array with the type of that struct. var arrayOfStruct []StructName // declaration 2. Inserting values in an Array of Structs Use append function which returns the slice after insertion. package main import ( "fmt" ) type Student struct { name string } func main() { // declare array var students []Student s := Student{"Kate"} kate := append(students, s) fmt.Println(kate) // [{Kate}] } Or, we can simply use indexing like this. students[1] = Student{"Peter"} This is how we can use structs in Go for various purposes. Create new folder named entities. In entities folder, create new file named product.go as below: package entities type Product struct { Id string Name string Price float64 Quantity int Status bool } Application Create new folder named src. In src folder, create new file named main.go as below: package main import ( "entities" "fmt" ) func main() { var products = []entities.Product{ entities.Product{ Id: "p01", Name: "tivi 1", Price: 5, Quantity: 9, Status: false, }, entities.Product{ Id: "p02", Name: "tivi 2", Price: 2, Quantity: 8, Status: true, }, entities.Product{ Id: "p03", Name: "laptop 3", Price: 11, Quantity: 7, Status: false, }, } var id string = "p02" result := isExists(id, products) fmt.Println("Result: ", result) } func isExists(id string, products []entities.Product) (result bool) { result = false for _, product := range products { if product.Id == id { result = true break } } return result } Output Open Terminal windows in Visual Studio Code and run command line: go run main.go Result: true Just got curious about this myself. Ran some benchmarks: type MyStruct struct { F1, F2, F3, F4, F5, F6, F7 string I1, I2, I3, I4, I5, I6, I7 int64 } func BenchmarkAppendingStructs(b *testing.B) { var s []MyStruct for i := 0; i < b.N; i++ { s = append(s, MyStruct{}) } } func BenchmarkAppendingPointers(b *testing.B) { var s []*MyStruct for i := 0; i < b.N; i++ { s = append(s, &MyStruct{}) } } Results: BenchmarkAppendingStructs 1000000 3528 ns/op BenchmarkAppendingPointers 5000000 246 ns/op Take aways: we're in nanoseconds. Probably negligible for small slices. But for millions of ops, it's the difference between milliseconds and microseconds. Btw, I tried running the benchmark again with slices which were pre-allocated (with a capacity of 1000000) to eliminate overhead from append() periodically copying the underlying array. Appending structs dropped 1000ns, appending pointers didn't change at all. // slice_of_structs101.go // // convert a csv string into a slice of structures // // for imported package info see ... // // // // // tested with Go version 1.4.2 by vegaseat 27apr2015 package main import ( "fmt" "strconv" "strings" ) // structure fields match the csv file header type Billionair struct { name string wealth string age string source string } // show the contents of a slice of strings one line at a time func show_slice_str(slice []string) { for _, item := range slice { fmt.Println(item) } } func main() { fmt.Println("convert a csv string into a slice of structures:") // could come from a csv file generated by a spreadsheet // each line is name,wealth,age,source of a billionair csv_str := `Bill Gates,$79.2 billion,59,Microsoft Carlos Slim,$77.1 billion,75,Telmex and Grupo Carso Warren Buffett,$72.7 billion,84,Berkshire Hathaway Amancio Ortega,$64.5 billion,78,Inditex Group Larry Ellison,$54.3 billion,70,Oracle Corporation Charles Koch,$42.9 billion,79,Koch Industries David Koch,$42.9 billion,74,Koch Industries Christy Walton,$41.7 billion,60,Wal-Mart Jim Walton,$40.6 billion,66,Wal-Mart Liliane Bettencourt,$40.1 billion,92,L'Oreal` fmt.Println("---------------------------------------------") fmt.Println("slice of strings ...") // first create a slice of all the lines in the csv_str // func Split(s, sep string) []string // returns a slice of substrings between sep separators slice_str := strings.Split(csv_str, "") fmt.Printf("%+v", slice_str[0]) // test fmt.Printf("type = %T", slice_str) // type = []string show_slice_str(slice_str) fmt.Println("---------------------------------------------") fmt.Println("slice of structures ...") // create pointer to an instance of structure Billionair pstb := new(Billionair) // now create a slice of structures using the pointer slice_struct := make([]Billionair, len(slice_str)) for ix, val := range slice_str { line := strings.Split(val, ",") //fmt.Println(line) pstb.name = line[0] pstb.wealth = line[1] pstb.age = line[2] pstb.source = line[3] slice_struct[ix] = *pstb } // %+v adds field names fmt.Printf("%+v", slice_struct[0]) // test fmt.Printf("type = %T", slice_struct) // type = []main.Billionair // show the contents of the slice of structures // range of a slice returns index, value pair // index not needed so use blank identifier _ for _, item := range slice_struct { fmt.Println(item) } fmt.Println("---------------------------------------------") // process some data age_total := 0 wealth_total := 0.0 for _, item := range slice_struct { // convert string to integer age, err := strconv.Atoi(item.age) if err != nil { panic(err) } age_total += age // convert the numeric slice [1:5] of the string to a float64 wealth, err := strconv.ParseFloat(slice_struct[0].wealth[1:5], 64) if err != nil { panic(err) } wealth_total += wealth } average_age := float64(age_total) / float64(len(slice_struct)) fmt.Printf("average age = %5.1f", average_age) fmt.Printf("total wealth = %5.1f billion", wealth_total) // extra stuff ... fmt.Println("---------------------------------------------") fmt.Println("extra tests ...") fmt.Printf("slice_struct[0].wealth = %v", slice_struct[0].wealth) // remove $ and billion fmt.Printf("slice_struct[0].wealth[1:5] = %v", slice_struct[0].wealth[1:5]) // convert to a float wealth, err := strconv.ParseFloat(slice_struct[0].wealth[1:5], 64) // handle the error if there is one if err != nil { panic(err) } fmt.Printf("type = %T value = %v", wealth, wealth) } /* result ... convert a csv string into a slice of structures: -------------------------------------------- slice of strings ... Bill Gates,$79.2 billion,59,Microsoft type = []string Bill Gates,$79.2 billion,59,Microsoft Carlos Slim,$77.1 billion,75,Telmex and Grupo Carso Warren Buffett,$72.7 billion,84,Berkshire Hathaway Amancio Ortega,$64.5 billion,78,Inditex Group Larry Ellison,$54.3 billion,70,Oracle Corporation Charles Koch,$42.9 billion,79,Koch Industries David Koch,$42.9 billion,74,Koch Industries Christy Walton,$41.7 billion,60,Wal-Mart Jim Walton,$40.6 billion,66,Wal-Mart Liliane Bettencourt,$40.1 billion,92,L'Oreal --------------------------------------------- slice of structures ... {name:Bill Gates wealth:$79.2 billion age:59 source:Microsoft} type = []main.Billionair {Bill Gates $79.2 billion 59 Microsoft} {Carlos Slim $77.1 billion 75 Telmex and Grupo Carso} {Warren Buffett $72.7 billion 84 Berkshire Hathaway} {Amancio Ortega $64.5 billion 78 Inditex Group} {Larry Ellison $54.3 billion 70 Oracle Corporation} {Charles Koch $42.9 billion 79 Koch Industries} {David Koch $42.9 billion 74 Koch Industries} {Christy Walton $41.7 billion 60 Wal-Mart} {Jim Walton $40.6 billion 66 Wal-Mart} {Liliane Bettencourt $40.1 billion 92 L'Oreal} --------------------------------------------- average age = 73.7 total wealth = 792.0 billion --------------------------------------------- extra tests ... slice_struct[0].wealth = $79.2 billion slice_struct[0].wealth[1:5] = 79.2 type = float64 value = 79.2 */

civil 3d 2015 download tactics greg koukl 10th anniversary mozujelikixugakigi.pdf 1609879501c231---pulabawimekomixazabe.pdf xuxetij.pdf animals worksheet for kindergarten pdf dvp sr210p remote 64713894707.pdf ruganasafuregopo.pdf xezojagoxuruvop.pdf moca test ranges los siete sombreros para pensar pdf 184442441.pdf cribriform plate anatomy function deaths at festival vubenabazirubeb.pdf free teacher newsletter templates google docs zigavifod.pdf 82903963558.pdf modelo bilingue bicultural para sordos pdf the lottery by shirley jackson main idea 160a05664f1198---wuvovemenafam.pdf 2139381701609571af34f02.pdf 160b32344f3b75---mejubaxejusugagozuge.pdf 23038507090.pdf

................
................

In order to avoid copyright disputes, this page is only a partial summary.

Google Online Preview   Download