本文整理汇总了Golang中fmt.Print函数的典型用法代码示例。如果您正苦于以下问题:Golang Print函数的具体用法?Golang Print怎么用?Golang Print使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了Print函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Golang代码示例。
示例1: TestLRUCache
func TestLRUCache(t *testing.T) {
strategy := NewLRUPeriodFlushStrategy(3, 100, 0)
storage := NewInMemoryKeyValueStorage(10)
flusher := &FakeFlusher{}
cache := NewKeyValueCache(storage, strategy, flusher)
fmt.Print("Start LRU cache test ...\t")
for i := 0; i < 10; i++ {
str := fmt.Sprint(i)
cache.Show(str, str)
}
keys, _ := cache.Keys()
if !same(convert2string([]int{7, 9, 8}), keys) {
t.Errorf("should be [7 8 9], but %v", keys)
}
if v, _ := cache.Get("1"); v != nil {
t.Errorf("%v should not be in cache", v)
}
cache.Get("7")
cache.Show("1", "1")
if v, _ := cache.Get("8"); v != nil {
keys, _ := cache.Keys()
t.Errorf("%v should not be in cache; cache content: %v", v, keys)
}
fmt.Print("OK\n")
}
开发者ID:notedit,项目名称:uniqush,代码行数:31,代码来源:kvcache_test.go
示例2: ExampleTerm_GetAll_optArgs
// Find all document with an indexed value.
func ExampleTerm_GetAll_optArgs() {
// Fetch the row from the database
res, err := DB("examples").Table("heroes").GetAll("man_of_steel").OptArgs(GetAllOpts{
Index: "code_name",
}).Run(session)
if err != nil {
fmt.Print(err)
return
}
defer res.Close()
if res.IsNil() {
fmt.Print("Row not found")
return
}
var hero map[string]interface{}
err = res.One(&hero)
if err != nil {
fmt.Printf("Error scanning database result: %s", err)
return
}
fmt.Print(hero["name"])
// Output: Superman
}
开发者ID:freedmand,项目名称:doc.vu,代码行数:27,代码来源:example_query_select_test.go
示例3: dump
func (char *Char) dump(s string) {
fmt.Print(s, " ");
for i := 0; i < len(char.field); i++ {
fmt.Printf("%s:%q ", fieldName[i], char.field[i])
}
fmt.Print("\n");
}
开发者ID:edisonwsk,项目名称:golang-on-cygwin,代码行数:7,代码来源:maketables.go
示例4: fail
func fail(run string, stdout, stderr bytes.Buffer) {
msg(fmt.Sprintf("Run %v stdout:", run))
fmt.Print(stdout.String())
msg(fmt.Sprintf("Run %v stderr:", run))
fmt.Print(stderr.String())
}
开发者ID:krisrang,项目名称:cirunner,代码行数:7,代码来源:main.go
示例5:
func (server *IpcServer)Connect() chan string {
session := make(chan string, 0)
go func(c chan string){
for{
request := <-c
if request == "CLOSE" {
break
}
var req Request
err := json.Unmarshal([]byte(request), &req)
if err != nil{
fmt.Println("Invalid request format:", request)
}
resp := server.Handle(req.Method, req.Params)
b, err := json.Marshal(resp)
c <- string(b)
}
fmt.Print("Session closed.")
}(session)
fmt.Print("A new session has been created.")
return session
}
开发者ID:lkj01010,项目名称:mygo01,代码行数:29,代码来源:server.go
示例6: printFields
func printFields(datamap map[string]interface{}, fields string) {
for k, v := range datamap {
key := ""
fieldsslice := strings.Split(fields, ",")
if fields != "_all" {
for _, rawfield := range fieldsslice {
field := strings.TrimSpace(rawfield)
if strings.EqualFold(field, strings.TrimSpace(k)) {
key = strings.TrimSpace(k)
}
}
} else {
key = k
}
if key != "" {
kp := strings.TrimSpace(key)
fmt.Print(kp)
fmt.Print(": ")
if key == "id" {
fmt.Print(int(v.(float64)))
} else {
fmt.Print(v)
}
fmt.Print("\n")
}
}
}
开发者ID:davidjohansson,项目名称:ecmd,代码行数:30,代码来源:article.go
示例7: Branch
func Branch(repo *libgit.Repository, args []string) {
switch len(args) {
case 0:
branches, err := repo.GetBranches()
if err != nil {
fmt.Fprintln(os.Stderr, "Could not get list of branches.")
return
}
head := getHeadBranch(repo)
for _, b := range branches {
if head == b {
fmt.Print("* ")
} else {
fmt.Print(" ")
}
fmt.Println(b)
}
case 1:
if head, err := getHeadId(repo); err == nil {
if cerr := libgit.CreateBranch(repo.Path, args[0], head); cerr != nil {
fmt.Fprintf(os.Stderr, "Could not create branch: %s\n", cerr.Error())
}
} else {
fmt.Fprintf(os.Stderr, "Could not create branch: %s\n", err.Error())
}
default:
fmt.Fprintln(os.Stderr, "Usage: go-git branch [branchname]")
}
}
开发者ID:driusan,项目名称:go-git,代码行数:30,代码来源:branch.go
示例8: main
func main() {
files, _ := filepath.Glob(path + "*")
namesSlice := []string{}
for _, basename := range files {
name := strings.TrimSuffix(basename, filepath.Ext(basename))
namesSlice = append(namesSlice, strings.Replace(name, path, "", -1))
}
fmt.Print("var ourskins = \"")
fmt.Print(strings.Join(namesSlice, ":"))
fmt.Println("\";")
fmt.Println("grabbing source from github")
return
/* a work in progress */
cmd := exec.Command("git", "clone", "https://github.com/electronoob/agarmods.git")
err := cmd.Start()
if err != nil {
fmt.Println("some dome error occured: ", err)
}
err = cmd.Wait()
if err != nil {
fmt.Println("Command finished with: ", err)
} else {
cmd := exec.Command("cp", "agarmods/mods.js", "mods.js")
cmd.Start()
cmd.Wait()
cmd = exec.Command("rm", "-rf", "agarmods")
cmd.Start()
cmd.Wait()
}
}
开发者ID:hakan39hakan,项目名称:agarmods,代码行数:31,代码来源:generate.go
示例9: main
func main() {
app := cli.NewApp()
app.Name = "qunosy" // ヘルプを表示する際に使用される
app.Usage = "print arguments" // ヘルプを表示する際に使用される
app.Version = "0.1.0" // ヘルプを表示する際に使用される
absPath, _ := filepath.Abs("../qunosy")
app.Action = func(c *cli.Context) { // コマンド実行時の処理
if len(c.Args()) > 1 {
if c.Args()[0] == "reload" {
fmt.Println("Reloading qiita log ...")
reload := exec.Command("sh", absPath+"/reload.sh", c.Args()[1])
reloadOut, err := reload.Output()
if err != nil {
fmt.Println(err.Error())
return
}
fmt.Print(string(reloadOut))
} else {
return
}
} else {
qunosy := exec.Command("sh", absPath+"/qunosy.sh")
qunosyOut, err := qunosy.Output()
if err != nil {
fmt.Println(err.Error())
return
}
fmt.Print(string(qunosyOut))
}
}
app.Run(os.Args)
}
开发者ID:falsandtru,项目名称:qunosy,代码行数:32,代码来源:qunosy.go
示例10: main
func main() {
// Socket to receive messages on
receiver, _ := zmq.NewSocket(zmq.PULL)
defer receiver.Close()
receiver.Bind("tcp://*:5558")
// Socket for worker control
controller, _ := zmq.NewSocket(zmq.PUB)
defer controller.Close()
controller.Bind("tcp://*:5559")
// Wait for start of batch
receiver.Recv(0)
// Start our clock now
start_time := time.Now()
// Process 100 confirmations
for task_nbr := 0; task_nbr < 100; task_nbr++ {
receiver.Recv(0)
if task_nbr%10 == 0 {
fmt.Print(":")
} else {
fmt.Print(".")
}
}
fmt.Println("\nTotal elapsed time:", time.Since(start_time))
// Send kill signal to workers
controller.Send("KILL", 0)
// Finished
time.Sleep(time.Second) // Give 0MQ time to deliver
}
开发者ID:patrickToca,项目名称:zmq3,代码行数:34,代码来源:tasksink2.go
示例11: printPath
func printPath(path []int, start int, end int) {
fmt.Print("[ ")
for i := start; i <= end; i++ {
fmt.Print(path[i], " ")
}
fmt.Print("]\n")
}
开发者ID:CR-Gjx,项目名称:ctci,代码行数:7,代码来源:question4_9.go
示例12: main
func main() {
b, err := ioutil.ReadFile("D:\\James\\Downloads\\kargerMinCut.txt")
if err != nil {
fmt.Println("Error:", err)
return
}
lines := strings.Split(string(b), "\n")
arr := make([][]int, 0, len(lines))
for _, v := range lines {
textints := strings.Split(v, "\t")
subarr := make([]int, 0, len(textints))
for _, w := range textints {
n, err := strconv.Atoi(w)
if err != nil {
fmt.Println("Error yo: ", err)
continue
}
subarr = append(subarr, n)
}
arr = append(arr, subarr)
}
for _, v := range arr {
for _, w := range v {
fmt.Print(w, "\t")
}
fmt.Print("\r\n")
}
}
开发者ID:JSoddy,项目名称:goplay,代码行数:31,代码来源:filetest3.go
示例13: main
func main() {
conn, err := net.Dial("tcp", "127.0.0.1:8081")
if err != nil {
fmt.Println("connect to server error!")
return
}
defer conn.Close()
message, _ := bufio.NewReader(conn).ReadString('\n')
fmt.Print(message)
for {
// read in input from stdin
reader := bufio.NewReader(os.Stdin)
fmt.Print("Text to send: ")
text, _ := reader.ReadString('\n')
// send to socket
_, _ = conn.Write([]byte(text))
//fmt.Fprintf(conn, text + "\n")
// listen for reply
message, _ := bufio.NewReader(conn).ReadString('\n')
if (message == "Good bye\n") {
break
} else {
fmt.Print("Message from server: " + message)
}
}
fmt.Println("conn is closed")
}
开发者ID:b96705008,项目名称:go-socket,代码行数:31,代码来源:test-client.go
示例14: main
func main() {
var infile = flag.String("infile", "input13.txt", "Input file")
flag.Parse()
f, err := os.Open(*infile)
if err != nil {
log.Fatal(err)
}
rdr := bufio.NewReader(f)
edges := make(map[string]map[string]int64)
for {
line, err := rdr.ReadString('\n')
if err == io.EOF {
break
}
if err != nil {
log.Fatal(err)
}
AddEdge(edges, line)
}
names := make([]string, len(edges))
i := 0
for name, _ := range edges {
names[i] = name
i++
if edges["me"] == nil {
edges["me"] = make(map[string]int64)
}
edges["me"][name] = 0
edges[name]["me"] = 0
}
names = append(names, "me")
fmt.Print("names: ", names, "\n")
fmt.Print(FindHappiest(edges, names))
}
开发者ID:cshabsin,项目名称:advent,代码行数:35,代码来源:day13.go
示例15: main
//A barebones IRC 'client' in the loosest sense of the word.
//Takes input from console. If command starts with a '/', everything after is sent as a raw IRC command.
//Otherwise the first argument is considered the channel/username, and the rest of the line is the message to send
// as a privmsg.
func main() {
flag.Parse()
fmt.Print("Simple Text-Based IRC Test Client\n\n")
fmt.Printf("Connecting to %s . . . \n", *address)
//LogClientHandler will handle printing out to stdio unless we change the default logger
client, err := irc.NewClient(*address, *ssl, irc.LogHandler)
if err != nil {
log.Fatalf("Error: %s", err.Error())
}
fmt.Print("Connected.\n\n")
client.Send(irc.UserMessage(*username, "host", "domain", "realname"))
client.Send(irc.NickMessage(*nick))
client.Send(irc.JoinMessage("#go_test"))
//Listen for input.
go readInput(client)
for { //Continuously read from the client until an error occurs
_, err := client.Read()
if err != nil {
fmt.Printf("ERROR: %s\n", err.Error())
fmt.Print("Exiting...")
return
}
}
}
开发者ID:Oooska,项目名称:irc,代码行数:35,代码来源:main.go
示例16: cmdExchange
func cmdExchange(cmd command) {
switch cmd.Action {
case "PRINT", "DISPLAY":
com.ColorLog("[%s] DEBUG( %s ) --> %s\n", levelToCmdFormat(cmd.Level),
getTitle(cmd), watchParametersToStr(cmd.Parameters))
case "BREAK":
if App.PrintStack {
com.ColorLog("[%s] BREAK:\n# %s #", levelToCmdFormat(cmd.Level),
cmd.Parameters["go.stack"])
if !App.SkipSuspend && App.PrintSource {
fmt.Print("press ENTER to view source...")
fmt.Scanln()
}
} else {
com.ColorLog("[%s] BREAK: 'print_stack' disenabled.\n",
levelToCmdFormat(cmd.Level))
}
if App.PrintSource {
line, _ := strconv.Atoi(cmd.Parameters["go.line"])
fmt.Println()
com.ColorLog("[%s] Source( %s ):\n%s", levelToCmdFormat(cmd.Level),
cmd.Parameters["go.file"], getFileSource(cmd.Parameters["go.file"], line))
}
if !App.SkipSuspend {
fmt.Print("press ENTER to continue...")
fmt.Scanln()
}
}
}
开发者ID:ccjimmy,项目名称:beewatch,代码行数:32,代码来源:watchpoint.go
示例17: Print
func (tokens LogTokens) Print() {
defer color.ResetColor()
var defColor color.Color = color.White
var defBright bool = true
for _, token := range tokens {
if token.Type >= TOKEN_DEBUG {
defColor, defBright, _ = token.Type.getFgColor()
}
}
for _, token := range tokens {
fg, bright, specific := token.Type.getFgColor()
if !specific {
fg = defColor
bright = defBright
}
color.Foreground(fg, bright)
fmt.Print(token.Text)
}
fmt.Print("\n")
}
开发者ID:kapitanov,项目名称:logtail,代码行数:25,代码来源:printer.go
示例18: Output
func (r Rspecish) Output(results <-chan []resource.TestResult, startTime time.Time) (exitCode int) {
testCount := 0
var failed []resource.TestResult
for resultGroup := range results {
for _, testResult := range resultGroup {
if testResult.Successful {
fmt.Printf(green("."))
} else {
fmt.Printf(red("F"))
failed = append(failed, testResult)
}
testCount++
}
}
fmt.Print("\n\n")
if len(failed) > 0 {
color.Red("Failures:")
for _, testResult := range failed {
fmt.Println(humanizeResult(testResult))
}
fmt.Print("\n")
}
fmt.Printf("Total Duration: %.3fs\n", time.Since(startTime).Seconds())
if len(failed) > 0 {
color.Red("Count: %d, Failed: %d\n", testCount, len(failed))
return 1
}
color.Green("Count: %d, Failed: %d\n", testCount, len(failed))
return 0
}
开发者ID:ryancox,项目名称:goss,代码行数:32,代码来源:rspecish.go
示例19: MustCheck
// MustCheck runs a consistency check on the database and panics if any errors are found.
func (db *TestDB) MustCheck() {
db.Update(func(tx *bolt.Tx) error {
// Collect all the errors.
var errors []error
for err := range tx.Check() {
errors = append(errors, err)
if len(errors) > 10 {
break
}
}
// If errors occurred, copy the DB and print the errors.
if len(errors) > 0 {
var path = tempfile()
tx.CopyFile(path, 0600)
// Print errors.
fmt.Print("\n\n")
fmt.Printf("consistency check failed (%d errors)\n", len(errors))
for _, err := range errors {
fmt.Println(err)
}
fmt.Println("")
fmt.Println("db saved to:")
fmt.Println(path)
fmt.Print("\n\n")
os.Exit(-1)
}
return nil
})
}
开发者ID:eswdd,项目名称:bosun,代码行数:33,代码来源:db_test.go
示例20: printDag
func printDag(nd *mdag.Node, ds mdag.DAGService, indent int) {
pbd, err := ft.FromBytes(nd.Data)
if err != nil {
panic(err)
}
for i := 0; i < indent; i++ {
fmt.Print(" ")
}
fmt.Printf("{size = %d, type = %s, children = %d", pbd.GetFilesize(), pbd.GetType().String(), len(pbd.GetBlocksizes()))
if len(nd.Links) > 0 {
fmt.Println()
}
for _, lnk := range nd.Links {
child, err := lnk.GetNode(context.Background(), ds)
if err != nil {
panic(err)
}
printDag(child, ds, indent+1)
}
if len(nd.Links) > 0 {
for i := 0; i < indent; i++ {
fmt.Print(" ")
}
}
fmt.Println("}")
}
开发者ID:djbarber,项目名称:ipfs-hack,代码行数:27,代码来源:dagmodifier_test.go
注:本文中的fmt.Print函数示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论