<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'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 (
"flag"
"fmt"
)
var foo struct {
A int
}
func main() {
flag.IntVar(&foo.A, "a", 3, "set a")
flag.Parse()
fmt.Println("a is:", foo.A)
}
</code></pre>
<p>Or maybe you'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 (
"encoding/json"
"log"
"os"
)
var foo struct {
A int
}
func main() {
// read json foo on stdin
d := json.NewDecoder(os.Stdin)
if err := d.Decode(&foo); err != nil {
log.Fatal("could not read json on stdin:", err)
}
// write to "foo.json"
w, err := os.Create("foo.json")
if err != nil {
log.Fatal(err)
}
defer w.Close()
b, err := json.Marshal(&foo)
if err != nil {
log.Fatal("could not marshal json:", err)
}
if _, err := w.Write(b); err != nil {
log.Fatal(err)
}
}
</code></pre>
<p>Sample usage:</p>
<pre><code>$ echo '{"A": 8}' | go run test.go
$ cat cat foo.json
{"A":8}
</code></pre></pre>
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889
- 请尽量让自己的回复能够对别人有帮助
- 支持 Markdown 格式, **粗体**、~~删除线~~、
`单行代码`
- 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
- 图片支持拖拽、截图粘贴等方式上传