How to set variables in a struct based on console input

agolangf · · 422 次点击    
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
<p>Hi I’m a noob and would like to know how to set the variables of a struct on console input thanks :) and if it’s possible to put that struct into a textfile</p> <hr/>**评论:**<br/><br/>justinisrael: <pre><p>Your question is both short and very broad. It actually covers a number of concepts, so any answer is likely going to be just as general. Have you tried anything yet? Here are the high level steps for you to Google:</p> <p>Reading input from stdin (<a href="https://tutorialedge.net/golang/reading-console-input-golang/" rel="nofollow">Example</a>)</p> <p>Convert a string to [type] (<a href="https://golang.org/pkg/strconv/" rel="nofollow">Example</a>)</p> <p>Encoding structs (<a href="https://gobyexample.com/json" rel="nofollow">Example </a>)</p> <p>Writing to a file (<a href="https://gobyexample.com/writing-files" rel="nofollow">Example </a>) </p></pre>ui7_uy8: <pre><blockquote> <p>Args hold the command-line arguments, starting with the program name.</p> </blockquote> <p><a href="https://golang.org/pkg/os/#pkg-variables" rel="nofollow">https://golang.org/pkg/os/#pkg-variables</a></p> <p><a href="https://golang.org/pkg/encoding/" rel="nofollow">https://golang.org/pkg/encoding/</a></p></pre>dilap: <pre><p>That&#39;s a bit vague. </p> <p>By console input do you mean like command-line flags?</p> <p>You could do something like</p> <pre><code>package main import ( &#34;flag&#34; &#34;fmt&#34; ) var foo struct { A int } func main() { flag.IntVar(&amp;foo.A, &#34;a&#34;, 3, &#34;set a&#34;) flag.Parse() fmt.Println(&#34;a is:&#34;, foo.A) } </code></pre> <p>Or maybe you&#39;d like to read text on stdin, and write to a file? Json would a handy format to do that.</p> <pre><code>package main import ( &#34;encoding/json&#34; &#34;log&#34; &#34;os&#34; ) var foo struct { A int } func main() { // read json foo on stdin d := json.NewDecoder(os.Stdin) if err := d.Decode(&amp;foo); err != nil { log.Fatal(&#34;could not read json on stdin:&#34;, err) } // write to &#34;foo.json&#34; w, err := os.Create(&#34;foo.json&#34;) if err != nil { log.Fatal(err) } defer w.Close() b, err := json.Marshal(&amp;foo) if err != nil { log.Fatal(&#34;could not marshal json:&#34;, err) } if _, err := w.Write(b); err != nil { log.Fatal(err) } } </code></pre> <p>Sample usage:</p> <pre><code>$ echo &#39;{&#34;A&#34;: 8}&#39; | go run test.go $ cat cat foo.json {&#34;A&#34;:8} </code></pre></pre>

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

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