person := struct { Id int Name string Email string }{ 1 , "Chang Sau Sheong" , "[email protected]" }
person = struct { Id int Name string Email string }{ Id : 1 , Name : "Chang Sau Sheong" , Email : "[email protected]" , }
There are a few use cases for anonymous structs but one particular case is pretty useful for bundling multiple pieces of unrelated data together to be sent to a function. Here’s a concrete example.
Say you want to send a struct to an HTML template such that an HTML page will be generated by substituting data from the struct into various locations in the template:
type Person struct { Id int Name string Email string } person := Person { 1 , "Chang Sau Sheong" , "[email protected]" } tpl := `<div> <div>{{ .Id }}</div> <div>{{ .Name }}</div> <div>{{ .Email }}</div> </div> ` templ := template . Must ( template . New ( "person" ). Parse ( tpl )) templ . Execute ( os . Stdout , person )
You have a template named tpl and want to substitute various pieces of data in it from a struct you pass to it. In this case, you pass the Person struct to the Execute method. The template will substitute the data at the various locations and if you run the preceding code, you will get this:
< div > < div > 1 </ div > < div > Chang Sau Sheong </ div > < div > [email protected] </ div > </ div >
This is all well and good but what if you want to display a piece of information on the same page that has nothing to do with a person, for example, a message for the user? You can’t add a field into the Person struct, as that would be silly and awkward. You could define another struct that wraps around the message and the Person struct but it’s only going to be used for that one single page. You have many other pages with other things to show besides the main piece of data. You can’t possibly define multiple structs, each to pass in some data to the page.
Here is where anonymous structs make a lot of sense:
type Person struct { Id int Name string Email string } person := Person { 1 , "Chang Sau Sheong" , "[email protected]" } tpl := `<h1>{{ .Message }}</h1> <div> <div>{{ .P.Id }}</div> <div>{{ .P.Name }}</div> <div>{{ .P.Email }}</div> </div> ` data := struct { P Person Message string }{ person , "Hello World!" } templ := template . Must ( template . New ( "person" ). Parse ( tpl )) templ . Execute ( os . Stdout , data )
Instead of sending in the Person struct, you create an anonymous struct that wraps around Person as well as a string message and send that in instead.
This way, you can preserve your defined structs and, if there are other pieces of data to send to the page, you can create an anonymous struct to wrap around the data and send that in.
标签:struct,person,Person,Go,div,data,Structs,string,Creating From: https://www.cnblogs.com/zhangzhihui/p/17746409.html