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


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

    ReplyDelete
  9. 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
  10. 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
  11. Я бы рекомендовал использовать профиль для светодиодных лент это нужно для того что бы лента дольше служила.

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

    ReplyDelete
  13. 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
  14. 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
  15. 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
  16. Home Mart is a site about Home Improvement, Furniture, Home Appliances and many more.
    Check out the best
    entertainment unit
    shoe rack

    ReplyDelete
  17. 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
  18. 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
  19. Thanks for sharing this such an informative and useful blog!
    You have a business and looking for the premier iPhone application development company in India, USA, UK that build extraordinary iPhone apps? You are the right place, We offer offshore iOS application development, app creation services at an affordable price.

    ReplyDelete
  20. Nice blog, it’s so knowledgeable, informative, and good looking site. I appreciate your hard work. Good job. Thank you for this wonderful sharing with us. Keep Sharing.
    Digital Marketing Course In Kolkata
    Web Design Course In Kolkata

    ReplyDelete
  21. 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
  22. wonderful article. Very interesting to read this article.I would like to thank you for the efforts you had made for writing this awesome article. This article resolved my all queries.
    Data Science Course

    ReplyDelete
  23. cool stuff you have and you keep overhaul every one of us

    Correlation vs Covariance

    ReplyDelete
  24. 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
  25. Very interesting to read this article.I would like to thank you for the efforts you had made for writing this awesome article. This article inspired me to read more. keep it up.
    Correlation vs Covariance
    Simple linear regression

    ReplyDelete
  26. 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
  27. It is perfect time to make some plans for the future and it is time to be happy. I've read this post and if I could I desire to suggest you some interesting things or suggestions. Perhaps you could write next articles referring to this article. I want to read more things about it!

    Data Science Training

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

    ReplyDelete
  29. Attend The Artificial Intelligence course From ExcelR. Practical Artificial Intelligence course Sessions With Assured Placement Support From Experienced Faculty. ExcelR Offers The Artificial Intelligence course.
    Artificial Intelligence Course

    ReplyDelete
  30. I feel very grateful that I read this. It is very helpful and very informative and I really learned a lot from it.

    Simple Linear Regression

    Correlation vs Covariance

    ReplyDelete
  31. Very interesting blog. Many blogs I see these days do not really provide anything that attracts others, but believe me the way you interact is literally awesome.You can also check my articles as well.

    Data Science In Banglore With Placements
    Data Science Course In Bangalore
    Data Science Training In Bangalore
    Best Data Science Courses In Bangalore
    Data Science Institute In Bangalore

    Thank you..

    ReplyDelete
  32. 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
  33. Very interesting to read this article.I would like to thank you for the efforts you had made for writing this awesome article. This article inspired me to read more. keep it up.
    Correlation vs Covariance
    Simple linear regression
    data science interview questions

    ReplyDelete
  34. 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
  35. Thanks for provide great informatic and looking beautiful blog, really nice required information & the things i never imagined and i would request, wright more blog and blog post like that for us. Thanks you
    DevOps Training in Chennai

    DevOps Online Training in Chennai

    DevOps Training in Bangalore

    DevOps Training in Hyderabad

    DevOps Training in Coimbatore

    DevOps Training

    DevOps Online Training

    ReplyDelete
  36. Nice article i was really impressed by seeing this article, it was very interesting and it is very useful for me.This is incredible,I feel really happy to have seen your webpage.I gained many unknown information, the way you have clearly explained is really fantastic.keep posting such useful information.
    Full Stack Training in Chennai | Certification | Online Training Course
    Full Stack Training in Bangalore | Certification | Online Training Course

    Full Stack Training in Hyderabad | Certification | Online Training Course
    Full Stack Developer Training in Chennai | Mean Stack Developer Training in Chennai
    Full Stack Training

    Full Stack Online Training




    ReplyDelete
  37. Good post found to be very impressive while going through this post. Thanks for sharing and keep posting such an informative content.

    Data Science Course in Raipur

    ReplyDelete
  38. 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
  39. 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
  40. Really nice and interesting post. I was looking for this kind of information and enjoyed reading this one. Keep posting. Thanks for sharing.

    data science interview questions

    ReplyDelete
  41. 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
  42. This post is very easy to read and appreciate without leaving any details. Great work! Great work!
    data science course in delhi

    ReplyDelete
  43. 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
  44. 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
  45. 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

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

    ReplyDelete
  47. 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, data sciecne course in hyderabad

    ReplyDelete
  48. 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
  49. 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, data scientist courses

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

    ReplyDelete
  51. I am looking for and I love to post a comment that "The content of your post is awesome" Great work!

    Simple Linear Regression

    Correlation vs Covariance

    ReplyDelete
  52. 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
  53. 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
  54. 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
  55. 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
  56. 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
  57. Get huge discount on Home and Kitchen Appliances,Split and Window Air Conditioner, Mobiles & Laptops online , Television, Speakers & more electronics at best price.
    voltas beko refrigerator

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

    ReplyDelete
  59. I want to leave a little comment to support and wish you the best of luck.we wish you the best of luck in all your blogging enedevors.
    data science in bangalore

    ReplyDelete
  60. Thanks for posting the best information and the blog is very helpful.data science interview questions and answers

    ReplyDelete
  61. i am glad to discover this page : i have to thank you for the time i spent on this especially great reading !! i really liked each part and also bookmarked you for new information on your site.
    cyber security training in bangalore

    ReplyDelete
  62. Truly mind blowing blog went amazed with the subject they have developed the content. These kind of posts really helpful to gain the knowledge of unknown things which surely triggers to motivate and learn the new innovative contents. Hope you deliver the similar successive contents forthcoming as well.

    data science certification in bhilai

    ReplyDelete
  63. I want to leave a little comment to support and wish you the best of luck.we wish you the best of luck in all your blogging enedevors.
    data science training in chennai

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

    ReplyDelete
  65. 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
  66. I want to leave a little comment to support and wish you the best of luck.we wish you the best of luck in all your blogging enedevors.
    business analytics courses

    ReplyDelete
  67. wonderful article. Very interesting to read this article. I would like to thank you for the efforts you had made for writing this awesome article. This article resolved my all queries. Mason Jacob

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

    ReplyDelete
  69. I want to leave a little comment to support and wish you the best of luck.we wish you the best of luck in all your blogging enedevors
    iot training in hyderabad

    ReplyDelete
  70. 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
  71. I want to leave a little comment to support and wish you the best of luck.we wish you the best of luck in all your blogging enedevors
    iot training in noida

    ReplyDelete
  72. Extremely overall quite fascinating post. I was searching for this sort of data and delighted in perusing this one. Continue posting. A debt of gratitude is in order for sharing. data analytics course in lucknow

    ReplyDelete
  73. I want to leave a little comment to support and wish you the best of luck.we wish you the best of luck in all your blogging enedevors
    data science training institute in delhi

    ReplyDelete
  74. Extremely overall quite fascinating post. I was searching for this sort of data and delighted in perusing this one. Continue posting. A debt of gratitude is in order for sharing.best data science courses in bangalore

    ReplyDelete
  75. Easily, the article is actually the best topic on this registry related issue. I fit in with your conclusions and will eagerly look forward to your next updates. data science course in mysore

    ReplyDelete
  76. Extraordinary blog went amazed with the content that they have developed in a very descriptive manner. This type of content surely ensures the participants to explore themselves. Hope you deliver the same near the future as well. Gratitude to the blogger for the efforts.

    Data Science Training

    ReplyDelete
  77. Stupendous blog huge applause to the blogger and hoping you to come up with such an extraordinary content in future. Surely, this post will inspire many aspirants who are very keen in gaining the knowledge. Expecting many more contents with lot more curiosity further.

    Data Science Certification in Bhilai

    ReplyDelete
  78. I want to leave a little comment to support and wish you the best of luck.we wish you the best of luck in all your blogging enedevors
    data scientist course in trivandrum

    ReplyDelete
  79. Impressive blog to be honest definitely this post will inspire many more upcoming aspirants. Eventually, this makes the participants to experience and innovate themselves through knowledge wise by visiting this kind of a blog. Once again excellent job keep inspiring with your cool stuff.

    Data Science Training in Bhilai

    ReplyDelete
  80. Wonderful blog found to be very impressive to come across such an awesome blog. I should really appreciate the blogger for the efforts they have put in to develop such an amazing content for all the curious readers who are very keen of being updated across every corner. Ultimately, this is an awesome experience for the readers. Anyways, thanks a lot and keep sharing the content in future too.

    Data Science Course in Bhilai

    ReplyDelete
  81. Extremely overall quite fascinating post. I was searching for this sort of data and delighted in perusing this one. Continue posting. A debt of gratitude is in order for sharing.data scientist course in warangal

    ReplyDelete
  82. He's really nice and mean. it's a really cool blog. The link is a very useful thing. You have really helped a lot of people who visit the blog and give them useful information. Data Science Training in Dombivli

    ReplyDelete
  83. I want to leave a little comment to support and wish you the best of luck.we wish you the best of luck in all your blogging enedevors
    data science course in thiruvananthapuram

    ReplyDelete
  84. I want to leave a little comment to support and wish you the best of luck.we wish you the best of luck in all your blogging enedevors
    data scientist course in delhi

    ReplyDelete
  85. I want to leave a little comment to support and wish you the best of luck.we wish you the best of luck in all your blogging enedevors
    business analytics course in varanasi

    ReplyDelete
  86. They're produced by the very best degree developers who will be distinguished for your polo dress creation. You'll find Ron Lauren inside an exclusive array which includes particular classes for men, women.
    business analytics course in hyderabad

    ReplyDelete
  87. 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
  88. We are really grateful for your blog post. You will find a lot of approaches after visiting your post. Great work Business Analytics Course in Vadodara

    ReplyDelete
  89. This post is very simple to read and appreciate without leaving any details out. Great work! PMP Training in Malaysia

    ReplyDelete
  90. I want to leave a little comment to support and wish you the best of luck.we wish you the best of luck in all your blogging enedevors
    data science training in delhi

    ReplyDelete
  91. 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
  92. Someone Sometimes with visits your blog regularly and recommended it in my experience to read as well. Data Science Course in Dehradun

    ReplyDelete
  93. I want to leave a little comment to support and wish you the best of luck.we wish you the best of luck in all your blogging enedevors
    data analytics course in faridabad

    ReplyDelete
  94. 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
  95. What a really awesome post this is. Truly, one of the best posts I've ever witnessed to see in my whole life. Wow, just keep it up. data analytics course

    ReplyDelete
  96. 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
  97. I want to leave a little comment to support and wish you the best of luck.we wish you the best of luck in all your blogging enedevors
    data analytics course in trivandrum

    ReplyDelete
  98. I want to leave a little comment to support and wish you the best of luck.we wish you the best of luck in all your blogging enedevors
    data science training in varanasi

    ReplyDelete
  99. I’m excited to uncover this page. I need to to thank you for ones time for this particularly fantastic read!! I definitely really liked every part of it and i also have you saved to fav to look at new information in your site. PMP Course

    ReplyDelete
  100. 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
  101. 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
  102. 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