• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Golang fmt.Println函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Golang中fmt.Println函数的典型用法代码示例。如果您正苦于以下问题:Golang Println函数的具体用法?Golang Println怎么用?Golang Println使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了Println函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Golang代码示例。

示例1: ExamplePayToAddrScript

// This example demonstrates creating a script which pays to a bitcoin address.
// It also prints the created script hex and uses the DisasmString function to
// display the disassembled script.
func ExamplePayToAddrScript() {
	// Parse the address to send the coins to into a btcutil.Address
	// which is useful to ensure the accuracy of the address and determine
	// the address type.  It is also required for the upcoming call to
	// PayToAddrScript.
	addressStr := "12gpXQVcCL2qhTNQgyLVdCFG2Qs2px98nV"
	address, err := btcutil.DecodeAddress(addressStr, &btcnet.MainNetParams)
	if err != nil {
		fmt.Println(err)
		return
	}

	// Create a public key script that pays to the address.
	script, err := btcscript.PayToAddrScript(address)
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Printf("Script Hex: %x\n", script)

	disasm, err := btcscript.DisasmString(script)
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println("Script Disassembly:", disasm)

	// Output:
	// Script Hex: 76a914128004ff2fcaf13b2b91eb654b1dc2b674f7ec6188ac
	// Script Disassembly: OP_DUP OP_HASH160 128004ff2fcaf13b2b91eb654b1dc2b674f7ec61 OP_EQUALVERIFY OP_CHECKSIG
}
开发者ID:stoiclabs,项目名称:blockchainr,代码行数:34,代码来源:example_test.go


示例2: TestSecureSecretoxKey

func TestSecureSecretoxKey(t *testing.T) {
	key1, ok := secretbox.GenerateKey()
	if !ok {
		fmt.Println("pwkey: failed to generate test key")
		t.FailNow()
	}

	skey, ok := SecureSecretboxKey(testPass, key1)
	if !ok {
		fmt.Println("pwkey: failed to secure secretbox key")
		t.FailNow()
	}

	key, ok := RecoverSecretboxKey(testPass, skey)
	if !ok {
		fmt.Println("pwkey: failed to recover box private key")
		t.FailNow()
	}

	if !bytes.Equal(key[:], key1[:]) {
		fmt.Println("pwkey: recovered  key doesn't match original")
		t.FailNow()
	}

	if _, ok = RecoverBoxKey([]byte("Password"), skey); ok {
		fmt.Println("pwkey: recover should fail with bad password")
		t.FailNow()
	}
}
开发者ID:postfix,项目名称:cryptobox-ng,代码行数:29,代码来源:pwkey_test.go


示例3: TestVersion

func TestVersion(t *testing.T) {
	v := new(Version)
	v.Version = uint16(1)
	v.Timestamp = time.Unix(0, 0)
	v.IpAddress = net.ParseIP("1.2.3.4")
	v.Port = uint16(4444)
	v.UserAgent = "Hello World!"

	verBytes := v.GetBytes()
	if len(verBytes) != verLen+12 {
		fmt.Println("Incorrect Byte Length: ", verBytes)
		t.Fail()
	}

	v2 := new(Version)
	err := v2.FromBytes(verBytes)
	if err != nil {
		fmt.Println("Error Decoding: ", err)
		t.FailNow()
	}

	if v2.Version != 1 || v2.Timestamp != time.Unix(0, 0) || v2.IpAddress.String() != "1.2.3.4" || v2.Port != 4444 || v2.UserAgent != "Hello World!" {
		fmt.Println("Incorrect decoded version: ", v2)
		t.Fail()
	}
}
开发者ID:msecret,项目名称:emp,代码行数:26,代码来源:objects_test.go


示例4: getUberCost

func getUberCost(start locationStruct, end locationStruct) (int, int, float64, string) {

	uberURL := strings.Replace(uberRequestURL, startLatitude, strconv.FormatFloat(start.Coordinate.Lat, 'f', -1, 64), -1)
	uberURL = strings.Replace(uberURL, startLongitude, strconv.FormatFloat(start.Coordinate.Lng, 'f', -1, 64), -1)
	uberURL = strings.Replace(uberURL, endLatitude, strconv.FormatFloat(end.Coordinate.Lat, 'f', -1, 64), -1)
	uberURL = strings.Replace(uberURL, endLongitude, strconv.FormatFloat(end.Coordinate.Lng, 'f', -1, 64), -1)

	res, err := http.Get(uberURL)

	if err != nil {

		//w.Write([]byte(`{    "error": "Unable to parse data from Google. Error at res, err := http.Get(url) -- line 75"}`))
		fmt.Println("Unable to parse data from Google. Error at res, err := http.Get(url) -- line 75")
		panic(err.Error())
	}

	body, err := ioutil.ReadAll(res.Body)
	if err != nil {

		//w.Write([]byte(`{    "error": "Unable to parse data from Google. body, err := ioutil.ReadAll(res.Body) -- line 84"}`))
		fmt.Println("Unable to parse data from Google. Error at res, err := http.Get(url) -- line 84")
		panic(err.Error())
	}

	var uberResult UberResults
	_ = json.Unmarshal(body, &uberResult)

	return uberResult.Prices[0].LowEstimate, uberResult.Prices[0].Duration, uberResult.Prices[0].Distance, uberResult.Prices[0].ProductID
}
开发者ID:savioferns321,项目名称:Uber_Trip_Requester,代码行数:29,代码来源:server.go


示例5: ExampleLambda_CreateFunction

func ExampleLambda_CreateFunction() {
	svc := lambda.New(session.New())

	params := &lambda.CreateFunctionInput{
		Code: &lambda.FunctionCode{ // Required
			S3Bucket:        aws.String("S3Bucket"),
			S3Key:           aws.String("S3Key"),
			S3ObjectVersion: aws.String("S3ObjectVersion"),
			ZipFile:         []byte("PAYLOAD"),
		},
		FunctionName: aws.String("FunctionName"), // Required
		Handler:      aws.String("Handler"),      // Required
		Role:         aws.String("RoleArn"),      // Required
		Runtime:      aws.String("Runtime"),      // Required
		Description:  aws.String("Description"),
		MemorySize:   aws.Int64(1),
		Publish:      aws.Bool(true),
		Timeout:      aws.Int64(1),
	}
	resp, err := svc.CreateFunction(params)

	if err != nil {
		// Print the error, cast err to awserr.Error to get the Code and
		// Message from an error.
		fmt.Println(err.Error())
		return
	}

	// Pretty-print the response data.
	fmt.Println(resp)
}
开发者ID:ernesto-jimenez,项目名称:goad,代码行数:31,代码来源:examples_test.go


示例6: main

func main() {
	file, err := os.Create("samp.txt")

	if err != nil {
		log.Fatal(err)
	}
	file.WriteString("This is some random text")
	file.Close()

	stream, err := ioutil.ReadFile("samp.txt")

	if err != nil {
		log.Fatal(err)
	}

	readString := string(stream)

	fmt.Println(readString)

	randInt := 5

	// randFloat := 10.5

	randString := "100"

	// randString2 := "250.5"

	fmt.Println(float64(randInt))
	newInt, _ := strconv.ParseInt(randString, 0, 64)
	newFloat, _ := strconv.ParseFloat(randString, 64)
	fmt.Println(newInt, newFloat)
}
开发者ID:girishpandit88,项目名称:goLangProjects,代码行数:32,代码来源:helloWorld6.go


示例7: main

func main() {
	consumer := consumer.New(dopplerAddress, &tls.Config{InsecureSkipVerify: true}, nil)
	consumer.SetDebugPrinter(ConsoleDebugPrinter{})

	messages, err := consumer.RecentLogs(appGuid, authToken)

	if err != nil {
		fmt.Printf("===== Error getting recent messages: %v\n", err)
	} else {
		fmt.Println("===== Recent logs")
		for _, msg := range messages {
			fmt.Println(msg)
		}
	}

	fmt.Println("===== Streaming metrics")
	msgChan, errorChan := consumer.Stream(appGuid, authToken)

	go func() {
		for err := range errorChan {
			fmt.Fprintf(os.Stderr, "%v\n", err.Error())
		}
	}()

	for msg := range msgChan {
		fmt.Printf("%v \n", msg)
	}
}
开发者ID:Reejoshi,项目名称:cli,代码行数:28,代码来源:main.go


示例8: main

func main() {
	var opts struct {
		ClientID     string `long:"client_id"     required:"true"`
		ClientSecret string `long:"client_secret" required:"true"`
	}
	_, err := flags.Parse(&opts)
	if err != nil {
		log.Fatalln(err)
		return
	}

	config := &oauth2.Config{
		ClientID:     opts.ClientID,
		ClientSecret: opts.ClientSecret,
		RedirectURL:  "urn:ietf:wg:oauth:2.0:oob",
		Scopes:       []string{"https://www.googleapis.com/auth/gmail.send"},
		Endpoint: oauth2.Endpoint{
			AuthURL:  "https://accounts.google.com/o/oauth2/auth",
			TokenURL: "https://accounts.google.com/o/oauth2/token",
		},
	}

	var code string
	url := config.AuthCodeURL("")
	fmt.Println("ブラウザで以下のURLにアクセスし、認証してCodeを取得してください。")
	fmt.Println(url)
	fmt.Println("取得したCodeを入力してください")
	fmt.Scanf("%s\n", &code)
	token, err := config.Exchange(context.Background(), code)
	if err != nil {
		log.Fatalln("Exchange: ", err)
	}
	fmt.Println("RefreshToken: ", token.RefreshToken)
}
开发者ID:mix3,项目名称:go-irc2mail,代码行数:34,代码来源:main.go


示例9: initDir

func initDir(args *argContainer) {
	err := checkDirEmpty(args.cipherdir)
	if err != nil {
		fmt.Printf("Invalid cipherdir: %v\n", err)
		os.Exit(ERREXIT_INIT)
	}

	// Create gocryptfs.conf
	cryptfs.Info.Printf("Choose a password for protecting your files.\n")
	password := readPasswordTwice(args.extpass)
	err = cryptfs.CreateConfFile(args.config, password, args.plaintextnames, args.scryptn)
	if err != nil {
		fmt.Println(err)
		os.Exit(ERREXIT_INIT)
	}

	if args.diriv && !args.plaintextnames {
		// Create gocryptfs.diriv in the root dir
		err = cryptfs.WriteDirIV(args.cipherdir)
		if err != nil {
			fmt.Println(err)
			os.Exit(ERREXIT_INIT)
		}
	}

	cryptfs.Info.Printf(colorGreen + "The filesystem has been created successfully.\n" + colorReset)
	cryptfs.Info.Printf(colorGrey+"You can now mount it using: %s %s MOUNTPOINT\n"+colorReset,
		PROGRAM_NAME, args.cipherdir)
	os.Exit(0)
}
开发者ID:thinkingo,项目名称:gocryptfs,代码行数:30,代码来源:main.go


示例10: txnCommandFunc

// txnCommandFunc executes the "txn" command.
func txnCommandFunc(c *cli.Context) {
	if len(c.Args()) != 0 {
		panic("unexpected args")
	}

	reader := bufio.NewReader(os.Stdin)

	next := compareState
	txn := &pb.TxnRequest{}
	for next != nil {
		next = next(txn, reader)
	}

	conn, err := grpc.Dial("127.0.0.1:12379")
	if err != nil {
		panic(err)
	}
	etcd := pb.NewEtcdClient(conn)

	resp, err := etcd.Txn(context.Background(), txn)
	if err != nil {
		fmt.Println(err)
	}
	if resp.Succeeded {
		fmt.Println("executed success request list")
	} else {
		fmt.Println("executed failure request list")
	}
}
开发者ID:royxhl,项目名称:etcd,代码行数:30,代码来源:txn_command.go


示例11: TestNew

func TestNew(t *testing.T) {
	config.SetHome(filepath.Join("..", "..", "cmd", "roy", "data"))
	mi, err := newMIMEInfo()
	if err != nil {
		t.Error(err)
	}
	tpmap := make(map[string]struct{})
	for _, v := range mi {
		//fmt.Println(v)
		//if len(v.Magic) > 1 {
		//	fmt.Printf("Multiple magics (%d): %s\n", len(v.Magic), v.MIME)
		//}
		for _, c := range v.Magic {
			for _, d := range c.Matches {
				tpmap[d.Typ] = struct{}{}
				if len(d.Mask) > 0 {
					if d.Typ == "string" {
						fmt.Println("MAGIC: " + d.Value)
					} else {
						fmt.Println("Type: " + d.Typ)
					}
					fmt.Println("MASK: " + d.Mask)
				}
			}
		}
	}
	/*
		for k, _ := range tpmap {
			fmt.Println(k)
		}
	*/
	if len(mi) != 1495 {
		t.Errorf("expecting %d MIMEInfos, got %d", 1495, len(mi))
	}
}
开发者ID:jhsimpson,项目名称:siegfried,代码行数:35,代码来源:mimeinfo_test.go


示例12: main

func main() {
	{
		errChan := make(chan error)
		go func() {
			errChan <- nil
		}()
		select {
		case v := <-errChan:
			fmt.Println("even if nil, it still receives", v)
		case <-time.After(time.Second):
			fmt.Println("time-out!")
		}
		// even if nil, it still receives <nil>
	}

	{
		errChan := make(chan error)
		errChan = nil
		go func() {
			errChan <- nil
		}()
		select {
		case v := <-errChan:
			fmt.Println("even if nil, it still receives", v)
		case <-time.After(time.Second):
			fmt.Println("time-out!")
		}
		// time-out!
	}
}
开发者ID:gyuho,项目名称:learn,代码行数:30,代码来源:27_receive_nil_from_channel.go


示例13: main

func main() {
	if Same(tree.New(1), tree.New(1)) && !Same(tree.New(1), tree.New(2)) {
		fmt.Println("PASSED")
	} else {
		fmt.Println("FAILED")
	}
}
开发者ID:fernandoalmeida,项目名称:studies,代码行数:7,代码来源:exercise-equivalent-binary-trees.go


示例14: ExampleExtractPkScriptAddrs

// This example demonstrates extracting information from a standard public key
// script.
func ExampleExtractPkScriptAddrs() {
	// Start with a standard pay-to-pubkey-hash script.
	scriptHex := "76a914128004ff2fcaf13b2b91eb654b1dc2b674f7ec6188ac"
	script, err := hex.DecodeString(scriptHex)
	if err != nil {
		fmt.Println(err)
		return
	}

	// Extract and print details from the script.
	scriptClass, addresses, reqSigs, err := btcscript.ExtractPkScriptAddrs(
		script, &btcnet.MainNetParams)
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println("Script Class:", scriptClass)
	fmt.Println("Addresses:", addresses)
	fmt.Println("Required Signatures:", reqSigs)

	// Output:
	// Script Class: pubkeyhash
	// Addresses: [12gpXQVcCL2qhTNQgyLVdCFG2Qs2px98nV]
	// Required Signatures: 1
}
开发者ID:stoiclabs,项目名称:blockchainr,代码行数:27,代码来源:example_test.go


示例15: NewWatcher

func NewWatcher(paths []string) {
	watcher, err := fsnotify.NewWatcher()
	if err != nil {
		log.Fatal(err)
	}

	go func() {
		for {
			select {
			case e := <-watcher.Event:
				fmt.Println(e)
				go Autobuild()
			case err := <-watcher.Error:
				log.Fatal("error:", err)
			}
		}
	}()
	for _, path := range paths {
		fmt.Println(path)
		err = watcher.Watch(path)
		if err != nil {
			log.Fatal(err)
		}
	}

}
开发者ID:zmdroid,项目名称:bee,代码行数:26,代码来源:watch.go


示例16: ExampleCloudFormation_EstimateTemplateCost

func ExampleCloudFormation_EstimateTemplateCost() {
	svc := cloudformation.New(nil)

	params := &cloudformation.EstimateTemplateCostInput{
		Parameters: []*cloudformation.Parameter{
			{ // Required
				ParameterKey:     aws.String("ParameterKey"),
				ParameterValue:   aws.String("ParameterValue"),
				UsePreviousValue: aws.Bool(true),
			},
			// More values...
		},
		TemplateBody: aws.String("TemplateBody"),
		TemplateURL:  aws.String("TemplateURL"),
	}
	resp, err := svc.EstimateTemplateCost(params)

	if err != nil {
		// Print the error, cast err to awserr.Error to get the Code and
		// Message from an error.
		fmt.Println(err.Error())
		return
	}

	// Pretty-print the response data.
	fmt.Println(resp)
}
开发者ID:ManifoldMike,项目名称:coreos-kubernetes,代码行数:27,代码来源:examples_test.go


示例17: Autobuild

func Autobuild() {
	defer func() {
		if err := recover(); err != nil {
			str := ""
			for i := 1; ; i += 1 {
				_, file, line, ok := runtime.Caller(i)
				if !ok {
					break
				}
				str = str + fmt.Sprintf("%v,%v", file, line)
			}
			builderror <- str

		}
	}()
	fmt.Println("Autobuild")
	path, _ := os.Getwd()
	os.Chdir(path)
	bcmd := exec.Command("go", "build")
	var out bytes.Buffer
	var berr bytes.Buffer
	bcmd.Stdout = &out
	bcmd.Stderr = &berr
	err := bcmd.Run()
	if err != nil {
		fmt.Println("run error", err)
	}
	if out.String() == "" {
		Kill()
	} else {
		builderror <- berr.String()
	}
}
开发者ID:zmdroid,项目名称:bee,代码行数:33,代码来源:watch.go


示例18: main

func main() {
	// Open device
	handle, err = pcap.OpenLive(device, snapshot_len, promiscuous, timeout)
	if err != nil {
		log.Fatal(err)
	}
	defer handle.Close()

	bpfInstructions := []pcap.BPFInstruction{
		{0x20, 0, 0, 0xfffff038}, // ld rand
		{0x54, 0, 0, 0x00000004},
		{0x15, 0, 1, 0x00000004},
		{0x06, 0, 0, 0x0000ffff},
		{0x06, 0, 0, 0000000000},
	}

	err = handle.SetBPFInstructionFilter(bpfInstructions)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println("Capturing ~4th packet (randomly).")

	packetSource := gopacket.NewPacketSource(handle, handle.LinkType())
	for packet := range packetSource.Packets() {
		// Do something with a packet here.
		fmt.Println(packet)
	}

}
开发者ID:breml,项目名称:mygoplayground,代码行数:29,代码来源:filter.go


示例19: ExampleLogAndNotFound

func ExampleLogAndNotFound() {
	// Note: The LogAnd* functions all work in a similar fashion.

	// Create an appengine context (in this case a mock one).
	c, err := appenginetesting.NewContext(nil)
	if err != nil {
		fmt.Println("creating context", err)
		return
	}
	defer c.Close()

	// Make the request and writer.
	w := httptest.NewRecorder()
	r, err := http.NewRequest("GET", "/example/test", nil)
	if err != nil {
		fmt.Println("creating request", err)
		return
	}

	// Simulate an error
	err = fmt.Errorf("WHERE ARE THEY TRYING TO GO? LOL")
	LogAndNotFound(c, w, r, err)

	// Print out what would be returned down the pipe.
	fmt.Println("Response Code:", w.Code)
	fmt.Println("Response Body:", w.Body.String())

	// Output:
	// Response Code: 404
	// Response Body: {"Type":"error","Message":"Not found."}
}
开发者ID:icub3d,项目名称:gorca,代码行数:31,代码来源:examples_test.go


示例20: writeInput

func writeInput(conn *net.TCPConn) {
	fmt.Print("Enter username: ")
	// Read from stdin.
	reader := bufio.NewReader(os.Stdin)
	username, err := reader.ReadString('\n')
	username = username[:len(username)-1]
	if err != nil {
		log.Fatal(err)
	}
	str, err := json.Marshal(map[string]interface{}{"username": string(username)})
	if err != nil {
		fmt.Println("It is not property name")
		return
	}
	err = common.WriteMsg(conn, string(str))
	if err != nil {
		log.Println(err)
	}
	fmt.Println("Enter text: ")
	for {
		text, err := reader.ReadString('\n')
		if err != nil {
			log.Fatal(err)
		}
		err = common.WriteMsg(conn, username+": "+text)
		if err != nil {
			log.Println(err)
		}
	}
}
开发者ID:chikilov,项目名称:goserver,代码行数:30,代码来源:main.go



注:本文中的fmt.Println函数示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Golang fmt.Scan函数代码示例发布时间:2022-05-24
下一篇:
Golang fmt.Printf函数代码示例发布时间:2022-05-24
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap