如何在Golang中使用for循环在struct中存储值

我想将值存储在结构中。 我有多个数据集,并且在迭代这些数据集时,我必须将这些数据集存储到struct中。

我还应该拥有先前存储的数据以及当前存储的数据。</ p>

请找到我正在使用的代码</ p>

 包main \  n import(
“ fmt”

类型saveDetails struct {
ID字符串
成绩字符串
常规字符串
OpeningKey字符串
}

func main(){
标签列表 := [] saveDetails {}
结果= [{{1000000001 B常规JOBOp234}} {{1000000003 C常规JOBOp456}}}

_,详细信息:=范围结果{

tagsList = append(tagsList,saveDetails {ID:details.ID,Grade:details.Grade,Regular:details.Regular,OpeningKey:details.OpeningKey})
}
fmt.Println(“ saveDetails:”,tagsList )
}
</ code> </ pre>

请帮助我解决此问题。 我对这个数组和golang中的结构是陌生的。 我不确定是否可以使用追加功能。 如果我得到了有效的代码,可能会很有帮助。</ p>
</ div>

展开原文

原文

I want to store values in a struct. I have multiple set of datas and while iterating those set of data, I have to store those sets into struct. I should also have the previous stored data along with the currently stored.

Please find the code i am using

    package main
    import (
      "fmt"
    )

    type saveDetails struct {
      ID string
      Grade string
      Regular string
      OpeningKey string
    }

    func main() {
       tagsList := []saveDetails {}
       results = [{ {1000000001 A Regular JOBOp123}} { {1000000002 B Regular JOBOp234}} { {1000000003 C  Regular JOBOp456}}]

       for _, details := range results {
          tagsList = append(tagsList, saveDetails {ID: details.ID, Grade:details.Grade, Regular:details.Regular, OpeningKey:details.OpeningKey})
       }
       fmt.Println("saveDetails :",tagsList )
     }

Please help me in resolving this issue. I am new to this array and structs in golang. I am not sure whether i could use the append function. It could be very much helpful if i get an working code.

2个回答



这是您代码的有效且有效的版本:</ p>

  package main \  n 
import(
“ fmt”

type saveDetails结构{
ID字符串
成绩字符串
常规字符串
OpeningKey字符串
}

func main(){
var标签列表 [] saveDetails
结果:= [] saveDetails {saveDetails {ID:“ 1000000001”,等级:“ A”,常规:“ Regular”,OpeningKey:“ JOBOp123”},saveDetails {ID:“ 1000000001”,等级:“ A“,常规:”常规“,OpeningKey:” JOBOp123“}}

表示_,详细信息:=范围结果{
tagsList = append(tagsList,saveDetails {
ID:details.ID,Grade:details .Grade,Regular:details.Regular,OpeningKey:details.OpeningKey,
})
}
fmt.Println(“ saveDetails:”,tagsList)
}
</ code> </ pre>

https://play.golang.org/p/vVQGPTnph6z </ p>
</ div>

展开原文

原文

This is a valid and working version of your code:

package main

import (
    "fmt"
)

type saveDetails struct {
    ID         string
    Grade      string
    Regular    string
    OpeningKey string
}

func main() {
    var tagsList []saveDetails
    results := []saveDetails{saveDetails{ID: "1000000001", Grade: "A", Regular: "Regular", OpeningKey: "JOBOp123"}, saveDetails{ID: "1000000001", Grade: "A", Regular: "Regular", OpeningKey: "JOBOp123"}}

    for _, details := range results {
        tagsList = append(tagsList, saveDetails{
            ID: details.ID, Grade: details.Grade, Regular: details.Regular, OpeningKey: details.OpeningKey,
        })
    }
    fmt.Println("saveDetails :", tagsList)
}

https://play.golang.org/p/vVQGPTnph6z

donglu8334
donglu8334 当然可以,只需编辑答案
一年多之前 回复
douxihui8270
douxihui8270 Pliutau,谢谢您的回复。 校正后的代码的输出为saveDetails:[{1000000001 A Regular JOBOp123}]。 从您的代码中是否还可以存储另一组数据(我的结果中有3组数据)?
一年多之前 回复



这里是解决您的问题的有效方法。 请注意,您的 results </ code>数组未正确声明。 在下面,您可以找到一个可行的解决方案,其中 tagsList </ code>的类型不是 array </ code>,而是使用通过 make()</ code>函数初始化的切片。 我建议使用切片,因为数组是值类型,因此在传递或设置新变量时总是复制。 切片只是对底层数组的引用(即指针),并且如果数组随着时间的流逝而变大,它们在性能方面具有各种优势。</ p>

 包main 

import(

“ fmt”

type saveDetails结构{
ID字符串
等级字符串
常规字符串
OpeningKey字符串
}

func main(){
tagsList:= make([ ] saveDetails,0)// 0是切片的初始大小
结果:= [] saveDetails {{“” 1000000001“,” A“,” Regular“,” JOBOp123“},{” 1000000002“,” B“ ,_,“ Regular”,“ JOBOp234”},{“ 1000000003”,“ C”,“ Regular”,“ JOBOp456”}}

_,详细信息:=范围结果{
tagsList = append(tagsList,saveDetails {ID:详细信息。ID,等级:详细信息。等级,常规:详细信息。常规,OpeningKey:详细信息。OpeningKey})
}
fmt.Println(“ saveDetails:”,tagsList)
}
</ code > </ pre>

https://play.golang.org/p/ Josvx49tNf6 </ p>
</ div>

展开原文

原文

Here is a working solution to your problem. Note that your results array was not correctly declared. Below you can find a working solution where the tagsList is not of type array but uses a slice that is initialized with the make() function. I would suggest using slices, as arrays are value types and therefore always copied when passed around or set under new variables. Slices are just references (i.e. a pointer) to underlying arrays and have various advantages in terms of performance if the array gets bigger as time passes.

package main

import (
    "fmt"
)

type saveDetails struct {
    ID         string
    Grade      string
    Regular    string
    OpeningKey string
}

func main() {
    tagsList := make([]saveDetails, 0) // 0 is the initial size of the slice
    results := []saveDetails{{"1000000001", "A", "Regular", "JOBOp123"}, {"1000000002", "B", "Regular", "JOBOp234"}, {"1000000003", "C", "Regular", "JOBOp456"}}

    for _, details := range results {
        tagsList = append(tagsList, saveDetails{ID: details.ID, Grade: details.Grade, Regular: details.Regular, OpeningKey: details.OpeningKey})
    }
    fmt.Println("saveDetails :", tagsList)
}

https://play.golang.org/p/Josvx49tNf6

duaijiao0648
duaijiao0648 感谢您的答复。 我将使用与我的代码相同的代码。
一年多之前 回复
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
其他相关推荐
在Golang中访问for循环之外的变量

<div class="post-text" itemprop="text"> <p>I'm trying to read a CSV file to store the values in a variable. However, I couldn't access the variables outside of the for loop </p> <pre><code>func GetKeys(filename string) { var record []string var err error file, err := os.Open(filename) if err != nil { log.Fatal(err) } defer file.Close() // Create a new reader. reader := csv.NewReader(bufio.NewReader(file)) for { record, err = reader.Read() // Stop at EOF. if err == io.EOF { break } fmt.Printf("%v", record) // works fine fmt.Printf("%v ", record[0]) // works fine too } fmt.Printf("%v ", record) // returns empty slice } func main() { GetKeys("credentials.csv") } </code></pre> </div>

Golang中的无限for循环[重复]

<div class="post-text" itemprop="text"> <div class="question-status question-originals-of-duplicate"> <p>This question already has an answer here:</p> <ul> <li> <a href="/questions/45137897/use-of-variable-in-for-loop-not-recognized-in-golang" dir="ltr">use of variable in for loop not recognized in Golang</a> <span class="question-originals-answer-count"> 1 answer </span> </li> </ul> </div> <p>I'm new to Golang, but I would expect not to have issues with something as basic as this.</p> <pre><code>package main import "fmt" func main() { s := make([]int, 0) s = append(s, 1) for len(s) != 0 { j := len(s) - 1 top, s := s[j], s[:j] fmt.Printf("top = %+v ", top) fmt.Printf("s = %+v ", s) fmt.Printf("len(s) = %+v ", len(s)) } } </code></pre> <p>This command doesn't exit, it just prints</p> <pre><code>len(s) = 0 top = 1 s = [] len(s) = 0 top = 1 s = [] len(s) = ^C </code></pre> <p>I find this stunning; what am I doing wrong? Syntactically, based on <a href="https://tour.golang.org/flowcontrol/3" rel="nofollow noreferrer">https://tour.golang.org/flowcontrol/3</a>, everything seems OK.</p> </div>

通过在golang中使用for循环来反转字符串效率低下?

<div class="post-text" itemprop="text"> <p>I did it like this Golang:</p> <pre><code>func reverseStr(str string) string { var reversed string for i := len(str) - 1; i &gt;= 0; i-- { reversed += string(str[i]) } return reversed } </code></pre> <p>I'm a beginner and can't do better for now, but I'm still learning. I'd like to know is my method less efficient than the ones I saw online that use runes:</p> <pre><code>func reverse(s string) string { chars := []rune(s) for i, j := 0, len(chars)-1; i &lt; j; i, j = i+1, j-1 { chars[i], chars[j] = chars[j], chars[i] } return string(chars) } </code></pre> </div>

在Golang中无法识别for循环中变量的使用

<div class="post-text" itemprop="text"> <p>I'm developing in golang and I run the following for loop:</p> <pre><code>// Define Initial Value i := 0 for { // Get Random data based on iteration data, i := GiveRandomData(i) // Save to database response, err := SaveToDatabase(data) if err != nil { log.Fatal(err) } fmt.Println(response) } </code></pre> <p>However, when compiling this program, I get the following error:</p> <blockquote> <p>.\main.go:26: i declared and not used</p> </blockquote> <p>The Golang compiler doesn't seem to recognise that the i variable is given back to the function in the next loop. Inside this function, the I variable changes value.</p> <p>What should I do to get rid of this compilation error or to let golang understand that this variable is NOT unused but used in the next iteration of this endless for loop?</p> </div>

在GoLang中的For循环中将值转换为字符串

<div class="post-text" itemprop="text"> <p>In GoLang I am looping through my form data like this, </p> <pre><code>for key, values := range r.Form { // range over map for _, value := range values { // range over []string fmt.Println(key, value) } } </code></pre> <p>I can print the data out to the terminal like this but I need this data to be a string so I can access it from outside of the for loop. </p> <p>How can I Put this in a variable that I can call outside of the for loop when the loop is finished?</p> <p>My goal here is to build a url by joining these three strings</p> <pre><code>var SearchUrl = "https://api.themoviedb.org/3/search/movie?query=" var MovieSearch []string = r.Form["GetSearchKey"] var apiKey = "&amp;api_key=e2a" UrlBuild := []string {SearchUrl, MovieSearch, apiKey} fmt.Println(UrlBuild) </code></pre> <p>I get this error</p> <pre><code>/main.go:71: cannot use MovieSearch (type []string) as type string in array or slice literal </code></pre> <p><code>MovieSearch</code> is coming from the input form. It is the search keywords.</p> <p>Once I have one string I can pass this to a function that makes the api call.</p> <p>The full function</p> <pre><code>func searchHandler(w http.ResponseWriter, r *http.Request) { display(w, "search", &amp;Page{Title: "Search"}) fmt.Println("method:", r.Method) r.ParseForm() fmt.Println("GetSearchKey:", r.Form["GetSearchKey"]) for key, values := range r.Form { // range over map for _, value := range values { // range over []string fmt.Println(key, value) } } var SearchUrl = "https://api.themoviedb.org/3/search/movie?query=" var MovieSearch []string = r.Form["GetSearchKey"] var apiKey = "&amp;api_key=ewrfwrfwrcwerc" UrlBuild := []string {SearchUrl, MovieSearch, apiKey} fmt.Println(UrlBuild) fmt.Println(reflect.TypeOf(r.Form["GetSearchKey"] )) } </code></pre> <p>The error comes from this line,</p> <pre><code>UrlBuild := []string {SearchUrl, MovieSearch, apiKey} </code></pre> </div>

在Golang中返回一个新的Struct实例

<div class="post-text" itemprop="text"> <p>My goal is to return a new DDIAddress from EndRangeTest(); however, when I try to do this, subsequent calls to EndRangeTest seem to modify the same struct instance instead of creating a new object. </p> <p>For instance, when I run the code below, I expect tRange to be 127.0.0.255 and sRange equal to 255.0.0.20. But what actually happens is that s.EndRangeTest() modifies tRange. </p> <pre><code>t := new(DDIAddress) s := new(DDIAddress) t.FromString("127.0.0.1") t.cidr = 24 s.FromString("255.0.0.20") s.cidr = 32 tRange := t.EndRangeTest() fmt.Printf("T Result:%s ", tRange.String()) sRange := s.EndRangeTest() fmt.Printf("S Result:%s ", sRange.String()) fmt.Printf("T Result:%s ", tRange.String()) </code></pre> <p>Output: </p> <pre><code>T Result:127.0.0.255 S Result:255.0.0.20 T Result:255.0.0.20 </code></pre> <p>I am new to Go, and don't understand what I am doing wrong here. </p> <p>My DDIAddress struct is implemented as followed:</p> <pre><code>type DDIAddress struct { net.IP cidr uint32 } func (addr *DDIAddress) EndRangeTest() (DDIAddress) { var maskSize int var start int endAddr := DDIAddress{} if addr.isIPv4() == false { maskSize = 16 start = 0 endAddr.IP = net.IPv6zero }else{ maskSize = 4 start = 12 endAddr.IP = net.IPv4zero } mask := net.CIDRMask(int(addr.cidr), 8*maskSize) for i :=0; i &lt; maskSize; i++{ endAddr.IP[start] = addr.IP[start] | (mask[i] ^ 0xff) start++ } return endAddr } </code></pre> <p>Thanks!</p> </div>

在for循环中使用指针-Golang

<div class="post-text" itemprop="text"> <p>I'm new to golang and struggling to understand why I have a bug in my code in one state but not the other. It's been a while since I've covered pointers, so I'm probably rusty!</p> <p>Basically I have a repository structure I'm using to store an object in memory, that has a <code>Store</code> function.</p> <pre><code>type chartsRepository struct { mtx sync.RWMutex charts map[ChartName]*Chart } func (r *chartsRepository) Store(c *Chart) error { r.mtx.Lock() defer r.mtx.Unlock() r.charts[c.Name] = c return nil } </code></pre> <p>So all it does is put a RW mutex lock on and adds the pointer to a map, referenced by an identifier.</p> <p>Then I've got a function that will basically loop through a slice of these objects, storing them all in the repository.</p> <pre><code>type service struct { charts Repository } func (svc *service) StoreCharts(arr []Chart) error { hasError := false for _, chart := range arr { err := svc.repo.Store(&amp;chart) // ... error handling } if hasError { // ... Deals with the error object return me } return nil } </code></pre> <p>The above doesn't work, it looks like everything works fine at first, but on trying to access the data later, the entries in the map all point to the same <code>Chart</code> object, despite having different keys.</p> <p>If I do the following and move the pointer reference to another function, everything works as expected:</p> <pre><code>func (svc *service) StoreCharts(arr []Chart) error { // ... for _, chart := range arr { err := svc.storeChart(chart) } // ... } func (svc *service) storeChart(c Chart) error { return svc.charts.Store(&amp;c) } </code></pre> <p>I'm assuming the issue is that because the loop overwrites the reference to the <code>chart</code> in the <code>for</code> loop, the pointer reference also changes. When the pointer is generated in an independent function, that reference is never overwritten. Is that right?</p> <p>I feel like I'm being stupid, but shouldn't the pointer be generated by <code>&amp;chart</code> and that's independent of the <code>chart</code> reference? I also tried creating a new variable for the pointer <code>p := &amp;chart</code> in the <code>for</code> loop and that didn't work either.</p> <p>Should I just avoid generating pointers in loops?</p> <p>Sorry for the multitude of questions, but I really want to get my head around this and I can't seem to find resources to explain this clearly.</p> <p>Thanks.</p> </div>

关于golang for循环的迭代值有些困惑

<div class="post-text" itemprop="text"> <p>This question is relate to <a href="https://stackoverflow.com/questions/15945030/change-values-while-iterating-in-golang">this</a> and <a href="https://stackoverflow.com/a/15952415/5938111">this answer</a></p> <p>All of these question &amp; answer all make sense to me except one little thing. </p> <p>If the 2nd value of for loop is a[i], then what is the different between the <code>a[i]</code> from the for loop and the <code>a[i]</code> as we write? It looks like the same thing but it isn't, right?</p> <p>Please help me clear this out. Thanks guys!</p> </div>

Golang中Struct的零值

<div class="post-text" itemprop="text"> <p>Here is sample code:</p> <pre><code>package main import ( "fmt" ) type A struct { Name string } func (this *A) demo(tag string) { fmt.Printf("%#v ", this) fmt.Println(tag) } func main() { var ele A ele.demo("ele are called") ele2 := A{} ele2.demo("ele2 are called") } </code></pre> <p>Run results:</p> <pre><code>&amp;main.A{Name:""} ele are called &amp;main.A{Name:""} ele2 are called </code></pre> <p>It looks like those are the same about <code>var ele A</code> and <code>ele2 := A{}</code></p> <p>So, the struct's Zero value is not <code>nil</code> , but a struct that all of the property are initialized Zero value. Is the guess right ?</p> <p>If the guess is right, then the nature of <code>var ele A</code> and <code>ele2 := A{}</code> are the same right ? I'm not sure.</p> </div>

我们如何在golang中的struct中初始化struct类型的数组(用于存储json输出)

<div class="post-text" itemprop="text"> <p>I need to initialize the following data structure which will store a json. The Attack_plans will hold multiple plans and if I loop through the GeneratePlan struct, I need all the plans that were stored.</p> <pre><code>type GeneratePlan struct { Mode string `json:"mode"` Name string `json:"name"` Schema string `json:"schema"` Version string `json:"version"` Attack_plans []struct { Attack_plan *Attack_plan `json:"attack-plan"` } `json:"attack-plans"` } type Attack_plan struct { Attack_resources []struct { Attack_resource *Attack_resource `json:"attack-resource"` } `json:"attack-resources"` } </code></pre> <p>Can anyone please suggest something? If the data structure needs to be simplified before initializing it, then please suggest that as well. I am very new to golang so please ignore the best practices to follow. Any help is appreciated. Thanks!</p> </div>

在struct golang中打印一个struct

<div class="post-text" itemprop="text"> <p>I want to print a certain item within a struct, that is within a struct. Example:<br> <strong>Pretend I have made up a blueprint struct, and are making an new one</strong><br> <strong>Pretend I have a myshapes struct, that contains a title, # of circles, and squares</strong> </p> <pre><code>car := blueprints{ dots: 5, lines: 25, shapes: []myshapes{ myshapes{ title:"car #1", circles:5, squares:7, }, myshapes{ title:"car #2", circles:2, squares:14, }, } </code></pre> <p>How do I print:</p> <pre><code>title:"car #1" circles:5 squares:7 title:"car #2" circles:2 squares:14 </code></pre> </div>

在Golang中将值追加到struct的struct会返回无效的内存地址

<div class="post-text" itemprop="text"> <p>I have a meal struct that "appends" another struct, except I want to add another struct "mealComponents".</p> <pre><code>type mealMain struct { *model.Meal Components []mealComponent `json:"components"` } type mealComponent struct { *model.MealComponent } </code></pre> <p>Where *model.Meal is as follows</p> <pre><code>type Meal struct { ID int64 `json:"id"` } </code></pre> <p>What I want is basically for "mealMain" struct to act like "Meal" struct, so that I can assign values and somehow append mealComponent as child (or maybe this is not a good idea? I'm open to suggestions)</p> <p>However when I do something like this</p> <pre><code>var meal mealMain meal.ID = 1 </code></pre> <p>It throws <code>runtime error: invalid memory address or nil pointer dereference</code> at meal.ID assignment.</p> <p>But if I do it like this:</p> <pre><code>type mealMain struct { MealMain *model.Meal `json:"meal_main"` Components []mealComponent `json:"components"` } </code></pre> <p>Then assign it this way:</p> <pre><code>var meal mealMain meal.mealMain.ID = 1 </code></pre> <p>It works properly, but I have the return json even deeper like this:</p> <pre><code>{ "MealModel": { "id": 1 } } </code></pre> <p>What I want is this:</p> <pre><code>{ "id": 1 } </code></pre> <p>Note: I want to avoid changing the model.</p> </div>

在golang中的struct内部定义和访问映射字段?

<div class="post-text" itemprop="text"> <p>Suppose I have a struct named Test,</p> <pre><code>type Test struct { Value1 int `json:"value1"` Value2 int `json:"Value2"` People map[string]string `json:"Value3"` Timeupdate string `json:"Timeupdate"` } </code></pre> <p>and people variable is a collection of key value pairs. How can I define and access people inside the struct?</p> <pre><code>var object = Test{Value1: arg1, Value2: arg2, People: args3, Timeupdate: time.Now().String()} </code></pre> <p>how can I define and access people inside this object?</p> </div>

如何在GoLang中覆盖组合的struct方法

<div class="post-text" itemprop="text"> <p>I want to make a controller <code>struct</code> in GoLang that has a <code>ServeHTTP</code> method which calls its own methods (which responds with a <code>405</code> status code) based on that of the HTTP request. New controllers should be able to inherit <code>ServeHTTP</code> while also being able to override methods like <code>Get(w http.ResponseWriter, r *http.Request)</code> and have the new ones being triggered by <code>ServeHTTP</code>. Then, controllers can be assigned as route handlers with the http module. I know how to do this in Java (have a controller superclass with all basic methods), but the method overriding part fails in Go. Here is my code:</p> <pre><code>package main import "net/http" type Controller struct { } func notAllowed(w http.ResponseWriter){ w.WriteHeader(http.StatusMethodNotAllowed) w.Write([]byte("405- Method Not Allowed")) } func(c Controller) Get(w http.ResponseWriter, r *http.Request){ notAllowed(w) } func(c Controller) Post(w http.ResponseWriter, r *http.Request){ notAllowed(w) } func(c Controller) Put(w http.ResponseWriter, r *http.Request){ notAllowed(w) } func(c Controller) Patch(w http.ResponseWriter, r *http.Request){ notAllowed(w) } func(c Controller) Delete(w http.ResponseWriter, r *http.Request){ notAllowed(w) } func(c Controller) ServeHTTP(w http.ResponseWriter, r *http.Request){ switch r.Method { case "GET": c.Get(w, r) case "POST": c.Post(w, r) case "PUT": c.Put(w, r) case "PATCH": c.Patch(w, r) case "DELETE": c.Delete(w, r) } } type Index struct { Controller } func(I Index) Get(w http.ResponseWriter, r http.Request){ w.Write([]byte("hello")) } func main(){ http.Handle("/", Index{}) http.ListenAndServe(":8080", nil) } </code></pre> </div>

Golang:如何从循环外部停止执行for循环?

<div class="post-text" itemprop="text"> <p>I am using an infinite for loop with a label. Outside the scope of the for loop, I have a scheduled function running as a go routine. I want to break the for loop from the scheduled function when a certain condition is met. How can I accomplish the same ? This is what I am trying, which obviously won't work due to scope issue.</p> <pre><code>package main import ( "fmt" "time" "sync" ) func main() { count := 0 var wg sync.WaitGroup wg.Add(1) t := time.NewTicker(time.Second*1) go func (){ for { fmt.Println("I will print every second", count) count++ if count &gt; 5 { break myLoop; wg.Done() } &lt;-t.C } }() i := 1 myLoop: for { fmt.Println("iteration", i) i++ } wg.Wait() fmt.Println("I will execute at the end") } </code></pre> </div>

在Golang中如何在其他包文件中使用struct?

<div class="post-text" itemprop="text"> <p>I am new in <strong>Golang</strong> and need some help.</p> <p>As you can see in the code below I am tring to create REST API in Golang. I use <code>mux</code> (Gorilla Mux) and <code>pq</code> (PostgreSQL driver) as third party libraries. Don't want to use ORM.</p> <p>Inside <code>application.go</code> file I have <code>InitializeRoutes</code> function with a list of all aviable routes. <code>GetFactors</code> function process one of these routes. I am tring to define <code>GetFactors</code> function logic in other file called <code>factors.go</code>. Inside <code>factors.go</code> file I want to use <code>Application</code> struct which was defined in <code>application.go</code>. How to make it correctly? Right now as you can see they are in different packages. For thats why <code>factors.go</code> file don't see <code>Application</code> struct.</p> <p><strong>Project structure</strong>:</p> <pre><code>main.go application.go controllers factors.go </code></pre> <p><strong>main.go:</strong></p> <pre><code>package main func main() { application := Application{} application.Initialization() application.Run("localhost:8000") } </code></pre> <p><strong>application.go</strong>:</p> <pre><code>package main import ( "database/sql" "github.com/gorilla/mux" "log" "net/http" "rest-api/configurations" ) type Application struct { Router *mux.Router Database *sql.DB } func (application *Application) Initialization() { var err error application.Database, err = configurations.DatabaseConnection() if err != nil { log.Fatal(err) } application.Router = mux.NewRouter() application.Router.StrictSlash(true) application.InitializeRoutes() } func (application *Application) Run(address string) { log.Fatal(http.ListenAndServe(address, application.Router)) } func (application *Application) InitializeRoutes() { application.Router.HandleFunc("/api/factors", application.GetFactors).Methods("GET") // other code } </code></pre> <p><strong>controllers/factors.go</strong>:</p> <pre><code>package controllers import ( "net/http" ) func (application *Application) GetFactors(rw http.ResponseWriter, request *http.Request) { // code } </code></pre> </div>

在Golang中的mongodb中插入struct

<div class="post-text" itemprop="text"> <p>I am trying to insert a struct in mongo database. </p> <pre><code>type SecretsStruct struct { UserID string `bson:"userid" json:"userid"` secretOne string `bson:"secret_one" json:secret_one` secretTwo string `bson:"secret_two" json:secret_two` secretThree string `bson:"secret_three" json:secret_three` } func (c *SecretsStruct) SetSecrets(userId string, encryptedKeys [][]byte){ c.UserID = userId c.secretOne = hex.EncodeToString(encryptedKeys[0]) c.secretTwo = hex.EncodeToString(encryptedKeys[1]) c.secretThree = hex.EncodeToString(encryptedKeys[2]) log.Printf("This is the c %s", c) } g := SecretsStruct{} g.SetSecrets(userStruct.UserID, encryptedKeys) err = secretCollection.Insert(g) if err != nil { panic(err) } </code></pre> <p>I have tried inserting the byte arrays corresponding to the secrets but of no help. The result which gets populated to the corresponding insertion operation is :</p> <pre><code>{'_id': ObjectId('5b80117c118c660aaa0c87c2'), 'userid': 'eb19d220-ef13-43aa-8a7f-f78637718000'} </code></pre> <p>On the other hand, if I try to insert same data with a map but without struct. </p> <pre><code>secretCollection.Insert(bson.M{"userid": userStruct.UserID, "secret_one": encryptedKeys[0], "secret_two": encryptedKeys[1], "secret_three": encryptedKeys[2]}) </code></pre> <p>The insertion operation executes successfully.</p> </div>

Golang动态创建成员Struct

<div class="post-text" itemprop="text"> <p>I am fairly new to Golang. I know there is Struct in Golang. But for all I know, you have to define struct </p> <pre><code>type Circle struct{ x,y,r float64 } </code></pre> <p>I am wondering how you can declare a new variable that doesn't exist in the Struct</p> <pre><code>circle := new(Cirlce) circle.color = "black" </code></pre> <p>Thx in advance.</p> </div>

如何动态清除golang中类型结构实例的值?

<div class="post-text" itemprop="text"> <p>Is it possible with golang to make a method that dynamically clears the values of a instance of a struct? btw Im new to golang.</p> <pre><code>type A struct { Name string Level int } type B struct { Skill string } func main() { a := A{"Momo", 1} b := B{"Starfall"} // outputs // {"Momo", 1} // {"Starfall"} clear(a) clear(b) // outputs // { , 0} // { } } func clear(v interface{}) { // some code } </code></pre> </div>

4小时玩转微信小程序——基础入门与微信支付实战

这是一个门针对零基础学员学习微信小程序开发的视频教学课程。课程采用腾讯官方文档作为教程的唯一技术资料来源。杜绝网络上质量良莠不齐的资料给学员学习带来的障碍。 视频课程按照开发工具的下载、安装、使用、程序结构、视图层、逻辑层、微信小程序等几个部分组织课程,详细讲解整个小程序的开发过程

Python可以这样学(第四季:数据分析与科学计算可视化)

董付国老师系列教材《Python程序设计(第2版)》(ISBN:9787302436515)、《Python可以这样学》(ISBN:9787302456469)配套视频,在教材基础上又增加了大量内容,通过实例讲解numpy、scipy、pandas、statistics、matplotlib等标准库和扩展库用法。

组成原理课程设计(实现机器数的真值还原等功能)

实现机器数的真值还原(定点小数)、定点小数的单符号位补码加减运算、定点小数的补码乘法运算和浮点数的加减运算。

javaWeb图书馆管理系统源码mysql版本

系统介绍 图书馆管理系统主要的目的是实现图书馆的信息化管理。图书馆的主要业务就是新书的借阅和归还,因此系统最核心的功能便是实现图书的借阅和归还。此外,还需要提供图书的信息查询、读者图书借阅情况的查询等

土豆浏览器

土豆浏览器可以用来看各种搞笑、电影、电视剧视频

Java面试题大全(2020版)

发现网上很多Java面试题都没有答案,所以花了很长时间搜集整理出来了这套Java面试题大全,希望对大家有帮助哈~ 本套Java面试题大全,全的不能再全,哈哈~ 一、Java 基础 1. JDK 和 JRE 有什么区别? JDK:Java Development Kit 的简称,java 开发工具包,提供了 java 的开发环境和运行环境。 JRE:Java Runtime Environ...

Java8零基础入门视频教程

这门课程基于主流的java8平台,由浅入深的详细讲解了java SE的开发技术,可以使java方向的入门学员,快速扎实的掌握java开发技术!

Java基础知识面试题(2020最新版)

文章目录Java概述何为编程什么是Javajdk1.5之后的三大版本JVM、JRE和JDK的关系什么是跨平台性?原理是什么Java语言有哪些特点什么是字节码?采用字节码的最大好处是什么什么是Java程序的主类?应用程序和小程序的主类有何不同?Java应用程序与小程序之间有那些差别?Java和C++的区别Oracle JDK 和 OpenJDK 的对比基础语法数据类型Java有哪些数据类型switc...

TTP229触摸代码以及触摸返回值处理

自己总结的ttp229触摸代码,触摸代码以及触摸按键处理

网络工程师小白入门--【思科CCNA、华为HCNA等网络工程师认证】

本课程适合CCNA或HCNA网络小白同志,高手请绕道,可以直接学习进价课程。通过本预科课程的学习,为学习网络工程师、思科CCNA、华为HCNA这些认证打下坚实的基础! 重要!思科认证2020年2月24日起,已启用新版认证和考试,包括题库都会更新,由于疫情原因,请关注官网和本地考点信息。题库网络上很容易下载到。

深度学习原理+项目实战+算法详解+主流框架(套餐)

深度学习系列课程从深度学习基础知识点开始讲解一步步进入神经网络的世界再到卷积和递归神经网络,详解各大经典网络架构。实战部分选择当下最火爆深度学习框架PyTorch与Tensorflow/Keras,全程实战演示框架核心使用与建模方法。项目实战部分选择计算机视觉与自然语言处理领域经典项目,从零开始详解算法原理,debug模式逐行代码解读。适合准备就业和转行的同学们加入学习! 建议按照下列课程顺序来进行学习 (1)掌握深度学习必备经典网络架构 (2)深度框架实战方法 (3)计算机视觉与自然语言处理项目实战。(按照课程排列顺序即可)

java jdk 8 帮助文档 中文 文档 chm 谷歌翻译

JDK1.8 API 中文谷歌翻译版 java帮助文档 JDK API java 帮助文档 谷歌翻译 JDK1.8 API 中文 谷歌翻译版 java帮助文档 Java最新帮助文档 本帮助文档是使用谷

Ubuntu18.04安装教程

Ubuntu18.04.1安装一、准备工作1.下载Ubuntu18.04.1 LTS2.制作U盘启动盘3.准备 Ubuntu18.04.1 的硬盘空间二、安装Ubuntu18.04.1三、安装后的一些工作1.安装输入法2.更换软件源四、双系统如何卸载Ubuntu18.04.1新的改变功能快捷键合理的创建标题,有助于目录的生成如何改变文本的样式插入链接与图片如何插入一段漂亮的代码片生成一个适合你的列...

快速排序---(面试碰到过好几次)

原理:    快速排序,说白了就是给基准数据找其正确索引位置的过程.    如下图所示,假设最开始的基准数据为数组第一个元素23,则首先用一个临时变量去存储基准数据,即tmp=23;然后分别从数组的两端扫描数组,设两个指示标志:low指向起始位置,high指向末尾.    首先从后半部分开始,如果扫描到的值大于基准数据就让high减1,如果发现有元素比该基准数据的值小(如上图中18&amp;lt...

手把手实现Java图书管理系统(附源码)

【超实用课程内容】 本课程演示的是一套基于Java的SSM框架实现的图书管理系统,主要针对计算机相关专业的正在做毕设的学生与需要项目实战练习的java人群。详细介绍了图书管理系统的实现,包括:环境搭建、系统业务、技术实现、项目运行、功能演示、系统扩展等,以通俗易懂的方式,手把手的带你从零开始运行本套图书管理系统,该项目附带全部源码可作为毕设使用。 【课程如何观看?】 PC端:https://edu.csdn.net/course/detail/27513 移动端:CSDN 学院APP(注意不是CSDN APP哦) 本课程为录播课,课程2年有效观看时长,大家可以抓紧时间学习后一起讨论哦~ 【学员专享增值服务】 源码开放 课件、课程案例代码完全开放给你,你可以根据所学知识,自行修改、优化 下载方式:电脑登录https://edu.csdn.net/course/detail/27513,点击右下方课程资料、代码、课件等打包下载

HTML期末大作业

这是我自己做的HTML期末大作业,花了很多时间,稍加修改就可以作为自己的作业了,而且也可以作为学习参考

Python数据挖掘简易入门

&nbsp; &nbsp; &nbsp; &nbsp; 本课程为Python数据挖掘方向的入门课程,课程主要以真实数据为基础,详细介绍数据挖掘入门的流程和使用Python实现pandas与numpy在数据挖掘方向的运用,并深入学习如何运用scikit-learn调用常用的数据挖掘算法解决数据挖掘问题,为进一步深入学习数据挖掘打下扎实的基础。

极简JAVA学习营第四期(报名以后加助教微信:eduxy-1)

想学好JAVA必须要报两万的培训班吗? Java大神勿入 如果你: 零基础想学JAVA却不知道从何入手 看了一堆书和视频却还是连JAVA的环境都搭建不起来 囊中羞涩面对两万起的JAVA培训班不忍直视 在职没有每天大块的时间专门学习JAVA 那么恭喜你找到组织了,在这里有: 1. 一群志同道合立志学好JAVA的同学一起学习讨论JAVA 2. 灵活机动的学习时间完成特定学习任务+每日编程实战练习 3. 热心助人的助教和讲师及时帮你解决问题,不按时完成作业小心助教老师的家访哦 上一张图看看前辈的感悟: &nbsp; &nbsp; 大家一定迫不及待想知道什么是极简JAVA学习营了吧,下面就来给大家说道说道: 什么是极简JAVA学习营? 1. 针对Java小白或者初级Java学习者; 2. 利用9天时间,每天1个小时时间; 3.通过 每日作业 / 组队PK / 助教答疑 / 实战编程 / 项目答辩 / 社群讨论 / 趣味知识抢答等方式让学员爱上学习编程 , 最终实现能独立开发一个基于控制台的‘库存管理系统’ 的学习模式 极简JAVA学习营是怎么学习的? &nbsp; 如何报名? 只要购买了极简JAVA一:JAVA入门就算报名成功! &nbsp;本期为第四期极简JAVA学习营,我们来看看往期学员的学习状态: 作业看这里~ &nbsp; 助教的作业报告是不是很专业 不交作业打屁屁 助教答疑是不是很用心 &nbsp; 有奖抢答大家玩的很嗨啊 &nbsp; &nbsp; 项目答辩终于开始啦 &nbsp; 优秀者的获奖感言 &nbsp; 这是答辩项目的效果 &nbsp; &nbsp; 这么细致的服务,这么好的氛围,这样的学习效果,需要多少钱呢? 不要1999,不要199,不要99,只要9.9 是的你没听错,只要9.9以上所有就都属于你了 如果你: 1、&nbsp;想学JAVA没有基础 2、&nbsp;想学JAVA没有整块的时间 3、&nbsp;想学JAVA没有足够的预算 还等什么?赶紧报名吧,抓紧抢位,本期只招300人,错过只有等时间待定的下一期了 &nbsp; 报名请加小助手微信:eduxy-1 &nbsp; &nbsp;

C++语言基础视频教程

C++语言基础视频培训课程:本课与主讲者在大学开出的程序设计课程直接对接,准确把握知识点,注重教学视频与实践体系的结合,帮助初学者有效学习。本教程详细介绍C++语言中的封装、数据隐藏、继承、多态的实现等入门知识;主要包括类的声明、对象定义、构造函数和析构函数、运算符重载、继承和派生、多态性实现等。 课程需要有C语言程序设计的基础(可以利用本人开出的《C语言与程序设计》系列课学习)。学习者能够通过实践的方式,学会利用C++语言解决问题,具备进一步学习利用C++开发应用程序的基础。

UnityLicence

UnityLicence

软件测试2小时入门

本课程内容系统、全面、简洁、通俗易懂,通过2个多小时的介绍,让大家对软件测试有个系统的理解和认识,具备基本的软件测试理论基础。 主要内容分为5个部分: 1 软件测试概述,了解测试是什么、测试的对象、原则、流程、方法、模型;&nbsp; 2.常用的黑盒测试用例设计方法及示例演示;&nbsp; 3 常用白盒测试用例设计方法及示例演示;&nbsp; 4.自动化测试优缺点、使用范围及示例‘;&nbsp; 5.测试经验谈。

YOLOv3目标检测实战:训练自己的数据集

YOLOv3是一种基于深度学习的端到端实时目标检测方法,以速度快见长。本课程将手把手地教大家使用labelImg标注和使用YOLOv3训练自己的数据集。课程分为三个小项目:足球目标检测(单目标检测)、梅西目标检测(单目标检测)、足球和梅西同时目标检测(两目标检测)。 本课程的YOLOv3使用Darknet,在Ubuntu系统上做项目演示。包括:安装Darknet、给自己的数据集打标签、整理自己的数据集、修改配置文件、训练自己的数据集、测试训练出的网络模型、性能统计(mAP计算和画出PR曲线)和先验框聚类。 Darknet是使用C语言实现的轻型开源深度学习框架,依赖少,可移植性好,值得深入探究。 除本课程《YOLOv3目标检测实战:训练自己的数据集》外,本人推出了有关YOLOv3目标检测的系列课程,请持续关注该系列的其它课程视频,包括: 《YOLOv3目标检测实战:交通标志识别》 《YOLOv3目标检测:原理与源码解析》 《YOLOv3目标检测:网络模型改进方法》 敬请关注并选择学习!

Python数据分析师-实战系列

系列课程主要包括Python数据分析必备工具包,数据分析案例实战,核心算法实战与企业级数据分析与建模解决方案实战,建议大家按照系列课程阶段顺序进行学习。所有数据集均为企业收集的真实数据集,整体风格以实战为导向,通俗讲解Python数据分析核心技巧与实战解决方案。

YOLOv3目标检测实战系列课程

《YOLOv3目标检测实战系列课程》旨在帮助大家掌握YOLOv3目标检测的训练、原理、源码与网络模型改进方法。 本课程的YOLOv3使用原作darknet(c语言编写),在Ubuntu系统上做项目演示。 本系列课程包括三门课: (1)《YOLOv3目标检测实战:训练自己的数据集》 包括:安装darknet、给自己的数据集打标签、整理自己的数据集、修改配置文件、训练自己的数据集、测试训练出的网络模型、性能统计(mAP计算和画出PR曲线)和先验框聚类。 (2)《YOLOv3目标检测:原理与源码解析》讲解YOLOv1、YOLOv2、YOLOv3的原理、程序流程并解析各层的源码。 (3)《YOLOv3目标检测:网络模型改进方法》讲解YOLOv3的改进方法,包括改进1:不显示指定类别目标的方法 (增加功能) ;改进2:合并BN层到卷积层 (加快推理速度) ; 改进3:使用GIoU指标和损失函数 (提高检测精度) ;改进4:tiny YOLOv3 (简化网络模型)并介绍 AlexeyAB/darknet项目。

超详细MySQL安装及基本使用教程

一、下载MySQL 首先,去数据库的官网http://www.mysql.com下载MySQL。 点击进入后的首页如下:  然后点击downloads,community,选择MySQL Community Server。如下图:  滑到下面,找到Recommended Download,然后点击go to download page。如下图:  点击download进入下载页面选择No...

一学即懂的计算机视觉(第一季)

图像处理和计算机视觉的课程大家已经看过很多,但总有“听不透”,“用不了”的感觉。课程致力于创建人人都能听的懂的计算机视觉,通过生动、细腻的讲解配合实战演练,让学生真正学懂、用会。 【超实用课程内容】 课程内容分为三篇,包括视觉系统构成,图像处理基础,特征提取与描述,运动跟踪,位姿估计,三维重构等内容。课程理论与实战结合,注重教学内容的可视化和工程实践,为人工智能视觉研发及算法工程师等相关高薪职位就业打下坚实基础。 【课程如何观看?】 PC端:https://edu.csdn.net/course/detail/26281 移动端:CSDN 学院APP(注意不是CSDN APP哦) 本课程为录播课,课程2年有效观看时长,但是大家可以抓紧时间学习后一起讨论哦~ 【学员专享增值服务】 源码开放 课件、课程案例代码完全开放给你,你可以根据所学知识,自行修改、优化 下载方式:电脑登录https://edu.csdn.net/course/detail/26281,点击右下方课程资料、代码、课件等打包下载

董付国老师Python全栈学习优惠套餐

购买套餐的朋友可以关注微信公众号“Python小屋”,上传付款截图,然后领取董老师任意图书1本。

爬取妹子图片(简单入门)

安装第三方请求库 requests 被网站禁止了访问 原因是我们是Python过来的 重新给一段 可能还是存在用不了,使用网页的 编写代码 上面注意看匹配内容 User-Agent:请求对象 AppleWebKit:请求内核 Chrome浏览器 //请求网页 import requests import re //正则表达式 就是去不规则的网页里面提取有规律的信息 headers = { 'User-Agent':'存放浏览器里面的' } response = requests.get

web网页制作期末大作业

分享思维,改变世界. web网页制作,期末大作业. 所用技术:html css javascript 分享所学所得

技术大佬:我去,你写的 switch 语句也太老土了吧

昨天早上通过远程的方式 review 了两名新来同事的代码,大部分代码都写得很漂亮,严谨的同时注释也很到位,这令我非常满意。但当我看到他们当中有一个人写的 switch 语句时,还是忍不住破口大骂:“我擦,小王,你丫写的 switch 语句也太老土了吧!” 来看看小王写的代码吧,看完不要骂我装逼啊。 private static String createPlayer(PlayerTypes p...

相关热词 c#树形选择 c#中类图的使用方法 c# 传参 调用exe c# 怎么定义方法 c# 修改本地时间 c#前台怎么读取资源文件 c# xml转list c#实现框选截图 m*m乘法表c# c# 乘法99表
立即提问