Pages

Saturday, October 11, 2014

How to Write Hello World in Go (in Go)

Let's write "hello world" in go.

Sure, you can do it this way:

package main

import "fmt"

func main() {
fmt.Printf("Hello world.\n")
}

But that's no fun, is it?
"Give a clever engineer a straightforward problem and they'll add complexity until it's interesting enough to solve."
Let's write a program that writes hello.go for us!  That's right: write go, using go.

(Sure, you could just write a program that echos the above source text as a quoted string to stdout, but that's not much fun. We must add more complexity to make it interesting.)

The "go/ast" package is used by gofmt and gofix (and various other tools) to parse and manipulate go source code in the form of abstract syntax trees.

We're going to build a new go program from scratch, in go, so we're not really interested in parsing so much as constructing an AST and printing the result as human-readable source code.

Here's a skeleton that uses go/ast to construct an AST for a very minimal go program that compiles, but doesn't actually do anything:

package main

import (
"bytes"
"fmt"
"go/ast"
"go/printer"
"go/token"
)

func main() {
// Start with a file
f := &ast.File{
Name: &ast.Ident{
// The package name is "main"
Name: "main",
},
// Top-level declarations in this file:
Decls: []ast.Decl{
// A basic func declaration with no receiver:
&ast.FuncDecl{
Name: &ast.Ident{
// This func is named "main"
Name: "main",
},
// With an empty func type (no params, no returns)
Type: &ast.FuncType{},
// And an empty body.
Body: &ast.BlockStmt{},
},
},
}

fset := token.NewFileSet()

var buf bytes.Buffer
printer.Fprint(&buf, fset, f)
fmt.Printf("%s\n", buf.String())
}

Try it out on play.golang.org here.  It produces the following:

package main

func main() {
}

Which does compile, but doesn't actually do anything.  Let's add the next pieces: The import statement for "fmt" and the fmt.Printf statement that actually prints "Hello world."

To add the import statement, add a new element to f.Decls:

// Start an "import" declaration
&ast.GenDecl{
Tok: token.IMPORT,
Specs: []ast.Spec{
&ast.ImportSpec{
// With a string literal of "fmt"
Path: &ast.BasicLit{
Kind:  token.STRING,
// Note the "" contained in ``
Value: `"fmt"`,
},
},
},
},

If you leave f.Decls as it is here and run it, it will produce the following:

package main

import "fmt"

func main() {
}

Which will fail to compile because "fmt" is unused.  So let's use it by adding the fmt.Printf statement inside the body of main(). Change the empty Body: &ast.BlockStmt{} in the above skeleton to include some ast.Stmts:

Body: &ast.BlockStmt{
List: []ast.Stmt{
// Start a stand-alone expression statement
&ast.ExprStmt{
// Representing a function call to "fmt"
X: &ast.CallExpr{
Fun: &ast.SelectorExpr{
X: &ast.Ident{
Name: "fmt",
},
// With a selector for Printf
Sel: &ast.Ident{
Name: "Printf",
},
},
// And a single-element arg list consisting of a string literal
Args: []ast.Expr{
&ast.BasicLit{
Kind:  token.STRING,
Value: `"Hello world.\n"`,
},
},
},
},
},
},

This will finally produce a runnable hello world:

package main

import "fmt"

func main() {
fmt.Printf("Hello world.\n")
}

Try the final product out on play.golang.org here.

In conclusion, if you'd like to do some code generation with go, this might not be a bad place to start. You can explore other parts of go/ast by adding some extra function declarations with actual parameter lists, return values and even receiver types, and then calling them from main.

If I was really bored, I'd write a further iteration of this program that constructs itself :)


42 comments:

  1. Thank you for your post. This was really an appreciating one. You done a good job. Keep on blogging like this unique information with us.


    Web Designing Training in Chennai

    ReplyDelete
  2. Wow amazing i saw the article with execution models you had posted. It was such informative. Really its a wonderful article. Thank you for sharing and please keep update like this type of article because i want to learn more relevant to this topic.

    SEO Company in Chennai

    ReplyDelete
  3. you had to share this style content is fantastic info for me.I'm read find that some content line very interesting.
    Hadoop Course in Chennai
    Hadoop Training in Chennai
    Informatica Training

    ReplyDelete

  4. excellent put up, very informative. I ponder why the other experts of this sector don't understand this. You should continue your writing. I am sure, you've a great readers' base already! outlook email login

    ReplyDelete
  5. Wow it is really wonderful and awesome thus it is very much useful for me to understand many concepts and helped me a lot. it is really explainable very well and i got more information from your blog.

    rpa training in chennai
    rpa training in bangalore
    rpa course in bangalore
    best rpa training in bangalore
    rpa online training

    ReplyDelete
  6. You blog post is just completely quality and informative. Many new facts and information which I have not heard about before. Keep sharing more blog posts.
    python course in pune
    python course in chennai
    python course in Bangalore

    ReplyDelete
  7. Thank you for allowing me to read it, welcome to the next in a recent article. And thanks for sharing the nice article, keep posting or updating news article.
    Best Devops training in sholinganallur
    Devops training in velachery
    Devops training in annanagar
    Devops training in tambaram

    ReplyDelete
  8. Hmm, it seems like your site ate my first comment (it was extremely long) so I guess I’ll just sum it up what I had written and say, I’m thoroughly enjoying your blog. I as well as an aspiring blog writer, but I’m still new to the whole thing. Do you have any recommendations for newbie blog writers? I’d appreciate it.
    AWS Interview Questions And Answers | AWS Interviews Questions and Answers for Devops | AWS interview questions and answers for Sysops
    AWS Interview questions and answers for freshers | AWS Interview Question for devops
    AWS Training in Bangalore with placements | AWS Training in Bangalore cost

    ReplyDelete
  9. This comment has been removed by the author.

    ReplyDelete
  10. I want to tell you how cool I spend my free time on this site is just super genteelonline slot games A bunch of slots and slot machines. Many people can even meet someone and of course have fun

    ReplyDelete
  11. Some us know all relating to the compelling medium you present powerful steps on this blog and therefore strongly encourage
    contribution from other ones on this subject while our own child is truly discovering a great deal.
    Have fun with the remaining portion of the year.

    Selenium training in bangalore | best selenium training in bangalore | advanced selenium training in bangalore | no.1 selenium training in bangalore

    ReplyDelete
  12. Я бы рекомендовал использовать профиль для светодиодных лент это нужно для того что бы лента дольше служила.

    ReplyDelete
  13. It is very good and very informative. There is a useful information in it.Thanks for posting...
    https://www.apponix.com/

    ReplyDelete
  14. Your blog is really useful for me. Thanks for sharing this useful blog..thanks for your knwoledge share ... superb article ... searching for this content.for so long.
    AWS Training Institute in Chennai | AWS Certification Training in Velachery | AWS Exam Center in Chennai | AWS Online Exams in Chennai

    ReplyDelete
  15. Your blog is very useful for me,thanks for sharing such a wonderful post with useful information.keep updating..
    Python Training Center in Chennai | Python Certification Training in Chennai

    ReplyDelete
  16. Attend The Python Training in Bangalore From ExcelR. Practical Python Training in Bangalore Sessions With Assured Placement Support From Experienced Faculty. ExcelR Offers The Python Training in Bangalore.

    ReplyDelete
  17. Home Mart is a site about Home Improvement, Furniture, Home Appliances and many more.
    Check out the best
    entertainment unit
    shoe rack

    ReplyDelete
  18. cool stuff you have and you keep Python classes in pune overhaul every one of us

    ReplyDelete
  19. Attend The Data Analytics Courses Online From ExcelR. Practical Data Analytics Courses Online Sessions With Assured Placement Support From Experienced Faculty. ExcelR Offers The Data Analytics Courses Online.
    ExcelR Data Analytics Courses Online

    ReplyDelete
  20. Awesome, Thanks for sharing this informative post. It is very interesting to read and helpful for me. Looking forward to read your future post. Keep sharing!!
    Artificial Intelligence Course

    ReplyDelete
  21. I have been reading for the past two days about your blogs and topics, still on fetching! Wondering about your words on each line was massively effective. Techno-based information has been fetched in each of your topics. Sure it will enhance and fill the queries of the public needs. Feeling so glad about your article. Thanks…!
    magento training course in chennai
    magento training institute in chennai
    magento 2 training in chennai
    magento development training
    magento 2 course
    magento developer training

    ReplyDelete