Created
August 29, 2018 06:50
-
-
Save fatkulnurk/216288a82e8103f42a63b37cbdaa8eb7 to your computer and use it in GitHub Desktop.
golang: fungsi untuk mendapatkan beberapa baris data inputan user di terminal / stdin
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"bufio" | |
"fmt" | |
"os" | |
"strings" | |
) | |
func ScanLn(rslt *[]interface{}) { | |
n := 0 | |
scanner := bufio.NewScanner(os.Stdin) | |
scanner.Split(func(data []byte, atEOF bool) (adv int, tkn []byte, err error) { | |
//callback ini dipanggil setiap pindah baris baru (user ketik Enter) | |
if atEOF { | |
*rslt = make([]interface{}, n) //menentukan alokasi memory yang dibutuhkan | |
i := 0 | |
for k := 0; k < n; k++ { | |
adv, tkn, err = bufio.ScanLines(data[i:], atEOF) | |
i += adv | |
(*rslt)[k] = string(tkn) | |
} | |
} | |
n++ | |
return | |
}) | |
scanner.Scan() | |
} | |
func main() { | |
println("inputkan beberapa baris data, akhiri dengan Ctrl-Z lalu Enter") | |
var result []interface{} | |
ScanLn(&result) | |
f := "hasil :\n" + strings.Repeat(", %s", len(result))[2:] + "\n" | |
fmt.Printf(f, result...) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment