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 :)


63 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. 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

  3. 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
  4. This comment has been removed by the author.

    ReplyDelete
  5. 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
  6. 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
  7. 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
  8. 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
  9. 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
  10. Home Mart is a site about Home Improvement, Furniture, Home Appliances and many more.
    Check out the best
    entertainment unit
    shoe rack

    ReplyDelete
  11. 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
  12. Very Useful article....Every year, Indian Post office Recruitment 2020 releases various job notifications to recruit eligible aspirants for various posts like a postman, postal assistants, sorting assistants, hindi typist, etc.

    ReplyDelete
  13. Awesome blog. I enjoyed reading your articles. This is truly a great read for me. I have bookmarked it and I am looking forward to reading new articles. Keep up the good work!

    Data Science Institute in Bangalore

    ReplyDelete
  14. Very informative post ! There is a lot of information here that can help any business get started with a successful social networking campaign !
    Data Science Certification in Bangalore

    ReplyDelete
  15. I see the greatest contents on your blog and I extremely love reading them.

    ReplyDelete
  16. very nice blogs!!! i have to learning for lot of information for this sites...Sharing for wonderful information.Thanks for sharing this valuable information to our vision. You have posted a trust worthy blog keep sharing.Your blog has very useful information about this technology which i am searching now, i am eagerly waiting to see your next post as soonI just got to this amazing site not long ago. I was actually captured with the piece of resources you have got here. Big thumbs up for making such wonderful blog page!Java training in Chennai

    Java Online training in Chennai

    Java Course in Chennai

    Best JAVA Training Institutes in Chennai

    Java training in Bangalore

    Java training in Hyderabad

    Java Training in Coimbatore

    Java Training

    Java Online Training

    ReplyDelete
  17. Really nice and interesting post. I was looking for this kind of information and enjoyed reading this one. Keep posting. Thanks for sharing.
    machine learning course training in guduvanchery

    ReplyDelete
  18. I might want to thank you for the endeavors you have made recorded as a hard copy of this article. Truth be told your exploratory writing capacities has propelled me to begin my own Blog Engine blog now. Actually the blogging is spreading its wings quickly. Your review is a fine case of it.data science course

    ReplyDelete
  19. I am really enjoying reading your well written articles. It looks like you spend a lot of effort and time on your blog. I have bookmarked it and I am looking forward to reading new articles. Keep up the good work.
    it course

    ReplyDelete
  20. 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...
    AWS Course in Bangalore

    AWS Course in Hyderabad

    AWS Course in Coimbatore

    AWS Course

    AWS Certification Course

    AWS Certification Training

    AWS Online Training

    AWS Training



    ReplyDelete
  21. This post is very easy to read and appreciate without leaving any details. Great work! Great work!
    data science course in delhi

    ReplyDelete
  22. This is a terrific article, and that I would really like additional info if you have got any. I’m fascinated with this subject and your post has been one among the simplest I actually have read.
    acte chennai

    acte complaints

    acte reviews

    acte trainer complaints

    acte trainer reviews

    acte velachery reviews complaints

    acte tambaram reviews complaints

    acte anna nagar reviews complaints

    acte porur reviews complaints

    acte omr reviews complaints

    ReplyDelete
  23. I was basically inspecting through the web filtering for certain data and ran over your blog. I am flabbergasted by the data that you have on this blog. It shows how well you welcome this subject. Bookmarked this page, will return for extra.
    what is hrdf

    ReplyDelete
  24. Am Divya,Am really impressed about this blog because this blog is very easy to learn and understand clearly.This blog is very useful for the college students and researchers to take a good notes in good manner,I gained many unknown information.

    Data Science Training In Chennai

    Data Science Online Training In Chennai

    Data Science Training In Bangalore

    Data Science Training In Hyderabad

    Data Science Training In Coimbatore

    Data Science Training

    Data Science Online Training

    ReplyDelete

  25. There is plainly a ton to consider this. Keep working, remarkable work!
    https://360digitmg.com/course/project-management-professional-pmp

    ReplyDelete
  26. I was looking at a portion of your posts on this site and I consider this site is really enlightening! Keep setting up..
    360DigiTMG big data course malaysia

    ReplyDelete
  27. Superb exertion to make this blog more awesome and appealing.
    hrdf claimable

    ReplyDelete
  28. A good blog always comes-up with new and exciting information and while reading I have feel that this blog is really have all those quality that qualify a blog to be a one.
    artificial intelligence course in bangalore

    ReplyDelete
  29. This knowledge.Excellently written article, if only all bloggers offered the same level of content as you, the internet would be a much better place. Please keep it up.
    data science training in hyderabad

    ReplyDelete
  30. I think this is an informative post and it is very useful and knowledgeable. therefore, I would like to thank you for the efforts you have made in writing this article.
    difference between analysis and analytics

    ReplyDelete
  31. If we paid that $1,000 with the end with the fifth year, we save $ 3449 in interest. canadian mortgage calculator Your Tangerine home loan repayments are calculated frist by determining your total mortgage amount. mortgage calculator canada

    ReplyDelete
  32. In fact it may be easier and simpler to teach a computer to learn, then add an actual organic brain. data science course in india

    ReplyDelete
  33. Amazing blog.Thanks for sharing such excellent information with us. keep sharing...
    digital marketing training in aurangabad

    ReplyDelete
  34. Thank you for taking the time to publish this information very useful!
    Python Training in Hyderabad
    Python Course in Hyderabad

    ReplyDelete
  35. I am impressed by the information that you have on this blog. It shows how well you understand this subject.
    Data Science Training in Hyderabad
    Data Science Course in Hyderabad

    ReplyDelete
  36. Greetings! Very helpful advicde in this particular post! It’s the little changes that make the greatest changes online cbd store

    ReplyDelete
  37. Nice this information is very useful. it is valuable and informative for me. Thanks for sharing these information with all of us. whatsapp mod

    ReplyDelete
  38. A good blog always comes-up with new and exciting information and while reading I feel that this blog really has all those qualities that qualify a blog to be one.
    data analytics course in hyderabad

    ReplyDelete
  39. We are really grateful for your blog post. You will find a lot of approaches after visiting your post. Great work
    full stack web development course in malaysia

    ReplyDelete
  40. I was eager to find this page. I needed to thank you for ones time for this especially awesome read!! I certainly truly preferred all aspects of it and I likewise have you book-set apart to look at new data in your blog.

    what does health insurance cover

    ReplyDelete
  41. This Is A Wonderful Article, Given So Much Info In It, These Type Of Articles Keeps The Users Interest In The Website, And Keep On Sharing More ... Good Luck. Data Science Course In Dehradun

    ReplyDelete
  42. Great post I would like to thank you for the efforts you have made in writing this interesting and knowledgeable article. data scientist course in kanpur

    ReplyDelete
  43. I have read your article; it is very informative and helpful for me. I admire the valuable information you offer in your articles. Thanks for posting it. data science course in surat

    ReplyDelete
  44. 360DigiTMG offers the best Data Science certification course in the market with placement assistance. Get trained by IIT, IIM, and ISB alumni.

    Business Analytics Course in Jodhpur

    ReplyDelete
  45. Nice blog! Actually, I am getting more information to read your great post. Thank you. Discover the ultimate resource for Article Submission Sites! Edtech Reader presents a meticulously curated list of high DA PA Article Submission Sites that can turbocharge your content marketing efforts.
    For more info visit High DA PA Article Submission Sites

    ReplyDelete