Stuck on something super simple

polaris · · 688 次点击    
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
<p>Still new to Go, feeling slightly discouraged at being stuck on this pretty trivial little problem.</p> <pre><code>package main import ( &#34;fmt&#34; &#34;net/http&#34; //&#34;time&#34; &#34;encoding/json&#34; &#34;github.com/jinzhu/gorm&#34; _ &#34;github.com/mattn/go-sqlite3&#34; &#34;github.com/zenazn/goji&#34; //&#34;github.com/zenazn/goji/web&#34; ) type Task struct { ID int64 `json:&#34;id&#34;` Name string `json:&#34;name&#34;` Description string `json:&#34;description&#34;` Code string `json:&#34;code&#34;` } var db gorm.DB func main() { db, err := gorm.Open(&#34;sqlite3&#34;, &#34;test.db&#34;) if err != nil { fmt.Printf(&#34;got an error opening the db\n&#34;) } db.LogMode(true) db.CreateTable(Task{}) defer db.Close() goji.Get(&#34;/&#34;, Root) goji.Get(&#34;/tasks&#34;, GetTasks) goji.Serve() } // Root path, does nothing really func Root(w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, &#34;hi&#34;) } func GetTasks(w http.ResponseWriter, r *http.Request) { tasks := []Task{} db.Find(&amp;tasks) json.NewEncoder(w).Encode(tasks) } </code></pre> <p>Seems super simple, Goji starts, I&#39;ve confirmed the db is there, and yet I get a &#34;panic: runtime error: invalid memory address or nil pointer dereference&#34; anytime I hit /tasks; seems like db.Find has a problem. What&#39;s up???</p> <hr/>**评论:**<br/><br/>paukul: <pre><p>You&#39;re shadowing the db variable so the global db is still uninitialized. change </p> <p><code>db, err :=</code> to <code> var err error db, err =... </code> And try again. At least that&#39;s my guess. I&#39;m on mobile sorry for the formatting</p></pre>panama_canals: <pre><p>That was 100% the issue; changed to: db, _ = gorm.Open(&#34;sqlite3&#34;, &#34;test.db&#34;) and it works. Thanks!</p></pre>ManticoreX: <pre><p>so you don&#39;t have to throw away the error, define var err Error on the line prior, and then you can do db, err = gorm....</p></pre>panama_canals: <pre><p>That&#39;s what I ended up doing, everything&#39;s cool now. I feel like I should be old enough to not be hassled by a scoping issue, but that&#39;s life I guess...</p></pre>habeyer: <pre><p>Very frustrating, I do that all the time</p></pre>RalphCorderoy: <pre><p><a href="http://www.qureet.com/blog/golang-beartrap/" rel="nofollow">http://www.qureet.com/blog/golang-beartrap/</a> is one explanation of this problem. (Disclosure: I read a draft.)</p></pre>consigntooblivion: <pre><p>Something I use is to print the object with the %#v format, which dumps the details. In your program I did:</p> <pre><code>fmt.Printf(&#34;\n\n%#v\n\n&#34;, db) </code></pre> <p>and got:</p> <pre><code>gorm.DB{Value:interface {}(nil), Error:error(nil), RowsAffected:0, callback:(*gorm.callback)(nil), db:gorm.sqlCommon(nil), parent:(*gorm.DB)(nil), search:(*gorm.search)(nil), logMode:0, logger:gorm.logger(nil), dialect:gorm.Dialect(nil), singularTable:false, source:&#34;&#34;, values:map[string]interface {}(nil), joinTableHandlers:map[string]gorm.JoinTableHandler(nil)} </code></pre> <p>I find it useful sometimes to see the details of the current value.</p></pre>

入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

688 次点击  
加入收藏 微博
暂无回复
添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传