Some examples
The previous program reads a file in its entirety, but a more common scenario is thatyou want to read a file on a line-by-line basis. The following snippet shows a wayto do just that (we’re discarding the error returned from os.Open
here to keepthe examples smaller – don’t ever do this in real life code).
f, _ := os.Open("/etc/passwd"); defer f.Close()
r := bufio.NewReader(f) 1
s, ok := r.ReadString('\n') 2
At 1 make f
a bufio
to have access to the ReadString
method. Then at 2 we reada line from the input, s
now holds a string which we can manipulate with, for instance,the strings
package.
A more robust method (but slightly more complicated) is ReadLine
, see the documentationof the bufio
package.
A common scenario in shell scripting is that you want to check if a directoryexists and if not, create one.
if [ ! -e name ]; then if f, e := os.Stat("name"); e != nil {
mkdir name os.Mkdir("name", 0755)
else } else {
# error // error
fi }
The similarity between these two examples (and with other scripting languages)have prompted comments that Go has a “script”-like feel to it, i.e. programmingin Go can be compared to programming in an interpreted language (Python, Ruby,Perl or PHP).