Golang FMT Package Using tips

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.

Golang FMT package using tips


GoLanguageFMTPackage implements a similar toCLanguageprintfAndscanfi/o The function. Format predicate with % Preamble, go verb " verbs from c is derived, but simpler. Here are some practical tips that have been used in the development process.

A hexadecimal print array or slice, each byte two characters, every two characters with a space interval

This function is used frequently in the development of communication protocol classes, the control commands and response information sent to terminal devices need to be printed in the log, or printed and received at debug time, usually these are in hexadecimal format and require a space interval between every two characters.

    Data: = []byte{1, 2, 4, 245, 241}    FMT. Printf ("% x\r\n", data)    FMT. Printf ("% x\r\n", data)

  

Output Result:


 on  Geneva Geneva  -  the  + F5 F1  on  Geneva Geneva  -  the  f5 F1


Output field name when two-dimensional structure is printed


typepersionstruct {    Name string age    int    ID string}    P: = persion{"Xiaoming", 12, "1302222222"}    FMT. Printf ("%v\r\n", p)    FMT. Printf ("%+v\r\n", p)

  

Output Result:

 A 1302222222 }{name:xiaoming Age: ID:1302222222}

the default %v print only values, %+v you can increase the structure field name



Triple-Reuse operand

Often, the same value occurs multiple times in formatted print content, and theGo language provides a mechanism for reusing the operands.

    x: = Int64 (0xdeadbeef)    FMT. Printf ("%d%[1]x%#[1]x%#[1]x\r\n", x)

  

Output results

3735928559 0xdeadbeef 0XDEADBEEF

Add a prefix when you print a value that is different from the binary

    x =    px: = &x    fmt. Printf ("% #d%#[1]o%#[1]b%#[1]x%#[1]x%p%#[2]p\r\n", x,px)

Output results

 $ 0310 11001000 0xc8 0XC8 0xc042040228 c042040228

#to be8increase in binary value0; for hexadecimal% #xIncrease0x; for hexadecimal% #XIncrease0X;% #psuppressed the0x;

# to decimal D and Binary b does not work.


Five printing complex structures


Complex structures are often used in the development process, with layers of nested structures in the structure, and the field is a pointer to the struct, and for such a field printf Prints the value of the pointer, which is not what we need.

For example, there are structural bodies used in development,Avro describes

{' type ': ' Record ',"Name": "Intersection","Fields" : [{"Name": "inter_id", "type": "int"},{"Name": "Name", "Type": "String"},{"Name": "Shape", "type": "int"},{"Name": "Primary_unit", "type": "int"},{"Name": "Unit_two", "type": "int"},{"Name": "Unit_three", "type": "int"},{"Name": "Longitude", "type": "Double"},{"Name": "Latitude", "type": "Double"},{"Name": "Entrances", "type": {"type": "Array", "Name": "", "items": {' type ': ' Record ',"Name": "Entrance","Fields" : [{"Name": "en_id", "type": "int"},{"Name": "Name", "Type": "String"},{"Name": "Degree", "type": "int"},{"Name": "Orientation", "type": "int"},{"Name": "Side_walks", "type": {"type": "Array", "Name": "", "items": {' type ': ' Record ',"Name": "Side_walk","Fields" : [{"Name": "id", "type": "int"}]}}},{"Name": "Motor_lanes", "type": {"type": "Array", "Name": "", "items": {' type ': ' Record ',"Name": "Motor_lane","Fields" : [{"Name": "id", "type": "int"},{"Name": "Lane_flow", "type": "int"},{"Name": "Has_waiting_area", "Type": "Boolean"}]}}},{"Name": "Non_motor_lanes", "type": {"type": "Array", "Name": "", "items": {' type ': ' Record ',"Name": "Non_motor_lane","Fields" : [{"Name": "id", "type": "int"},{"Name": "Lane_flow", "type": "int"}]}}},{"Name": "Exit_lanes", "type": {"type": "Array", "Name": "", "items": {' type ': ' Record ',"Name": "Exit_lane","Fields" : [{"Name": "id", "type": "int"},{"Name": "Lane_flow", "type": "int"}]}}},{"Name": "Exit_non_motor_lanes", "type": {"type": "Array", "Name": "", "Items": "Non_motor_lane"}}]}}}]}


The generated code is as follows (partially omitted)


typeintersectionstruct {    interid int32 ' json: ' inter_id ' xorm: ' pk notnull ' '    name string ' JSON: ' Name ' '    Shape int32 ' JSON: ' Shape ' '    primaryunit int32 ' json: ' Primary_unit ' '    unittwo int32 ' json: ' Unit_two    ' Unitthree int32 ' JSON: "Unit_three" '    longitude float64 ' JSON: "Longitude" '    Latitude float64 ' JSON: "Latitude" '    entrances []*entrance ' JSON: "Entrances" xorm: "-" '}typeentrancestruct {    interid int32 ' JSON: "-" Xorm: "PK Notnull "'    EnID int32 ' JSON:" en_id "Xorm:" PK notnull "'    name string ' JSON:" name "'    degree int32 ' JSON:" Degree "'    Orientation int32 ' JSON:" Orientation "'    sidewalks []*sidewalk ' json: ' side_walks ' xorm: '-' '    Motorlanes []*motorlane ' JSON: "Motor_lanes" Xorm: "-" '    nonmotorlanes []*nonmotorlane ' JSON: "Non_motor_lanes" Xorm: "-" '    exitlanes []*exitlane ' JSON: "Exit_lanes" Xorm: "-" '    exitnonmotorlanes []*nonmotorlaneexit ' JSON: "Exit_non_motor_lanes" Xorm: "-" '}

  

If you print, the output has only one layer of structure, and the nested parts only have pointer values.


There are two ways to print the full result: one is to use reflection to implement a custom print for deep printing, and the other is to take advantage of the JSON package.

    Bdata, _: = json. Marshalindent (dbconf, "", "\ T")    FMT. Println (String (bdata))

  

Six Terminal program print wait


Often write tool software, if it takes a long time, increasing the waiting output will improve the user experience. The following is an example of "Go language Programming".

Package Mainimport (    "FMT"    "Time") Func main () {    go spinner. Millisecond)    Const n =    fibn: = FIB (n)//slow    FMT. Printf ("\rfibonacci (%d) =%d\n", N, fibn)}func spinner (delay time.) Duration) {    for {        for _, R: = Range '-\|/' {            fmt. Printf ("\r%c", R) time            . Sleep (delay)        }    }}func fib (x int) int {    If x < 2 {        return x    }    return fib (x-1) + fib (x-2)}

  

Fibonacci functions are slow to calculate, turn on goroutine for print wait symbols, and exit when the calculation is complete.



















Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.