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


105 comments:

  1. Replies
    1. IEEE Final Year projects Project Center in Chennai are consistently sought after. Final Year Students Projects take a shot at them to improve their aptitudes. Final Year Project Domains for IT

      JavaScript Training in Chennai

      JavaScript Training in Chennai

      The Angular Training covers a wide range of topics including Components, project projects for cse. Angular Training

      Delete
  2. 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
  3. 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
  4. 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

  5. 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
  6. 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
  7. 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
  8. 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
  9. 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
  10. This comment has been removed by the author.

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

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

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

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

    ReplyDelete
  20. 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
  21. 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
  22. 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
  23. 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

  24. You write this post very carefully I think, which is easily understandable to me. Not only this, but another post is also good. As a newbie, this info is really helpful for me. Thanks to you.
    Tally ERP 9 Training
    tally classes
    Tally Training institute in Chennai
    Tally course in Chennai

    ReplyDelete
  25. 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
  26. 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
  27. This is a wonderful article. I really enjoyed reading this article. Thanks for sharing such detailed information.
    Data Science Course in Marathahalli
    Data Science Course Training in Bangalore

    ReplyDelete
  28. Actually I read it yesterday but I had some thoughts about it and today I wanted to read it again because it is very well written.

    data science course

    ReplyDelete
  29. 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
  30. cool stuff you have and you keep overhaul every one of us

    Correlation vs Covariance

    ReplyDelete
  31. 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
  32. Excellent Blog! I would like to thank for the efforts you have made in writing this post. I am hoping the same best work from you in the future as well. I wanted to thank you for this websites! Thanks for sharing. Great websites!
    Data Science Institute in Bangalore

    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

    ReplyDelete
  34. I was very pleased to find this site.I wanted to thank you for this great read!! I definitely enjoying every little bit of it and I have you bookmarked to check out new stuff you post.
    Data Science Course in Bangalore

    ReplyDelete
  35. I don t have the time at the moment to fully read your site but I have bookmarked it and also add your RSS feeds. I will be back in a day or two. thanks for a great site.
    Data Science Training in Bangalore

    ReplyDelete
  36. 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
  37. Took me time to understand all of the comments, but I seriously enjoyed the write-up. It proved being really helpful to me and Im positive to all of the commenters right here! Its constantly nice when you can not only be informed, but also entertained! I am certain you had enjoyable writing this write-up.

    Data Science Course

    ReplyDelete
  38. 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
  39. I see the greatest contents on your blog and I extremely love reading them.

    ReplyDelete
  40. 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
  41. 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
  42. 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
  43. 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
  44. 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
  45. Nice post. Thanks for sharing! I want people to know just how good this information is in your article. It’s interesting content and Great work.Very useful and informative content has been shared out here, Thanks for sharing it


    Azure Training in Chennai

    Azure Training in Bangalore

    Azure Training in Hyderabad

    Azure Training in Pune

    Azure Training | microsoft azure certification | Azure Online Training Course

    Azure Online Training

    ReplyDelete
  46. 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
  47. 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
  48. Amazing post found to be very impressive while going through this post. Thanks for sharing and keep posting such an informative content.

    360DigiTMG PMP Certification Course

    ReplyDelete
  49. Great blog found to be well written in a simple manner that everyone will understand and gain the enough knowledge from your blog being more informative is an added advantage for the users who are going through it. Once again nice blog keep it up.

    360DigiTMG Python Course

    ReplyDelete
  50. 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
  51. 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
  52. 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
  53. I feel really happy to have seen your webpage.I am feeling grateful to read this.you gave a nice information for us.please updating more stuff content...keep up!!

    Android Training in Chennai

    Android Online Training in Chennai

    Android Training in Bangalore

    Android Training in Hyderabad

    Android Training in Coimbatore

    Android Training

    Android Online Training

    ReplyDelete
  54. 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
  55. 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
  56. 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

    KNN Algorithm

    Logistic Regression explained

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

    ReplyDelete
  59. 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
  60. Good Post! Thank you so much for sharing this pretty post, it was so good to read and useful to improve my knowledge as updated one, keep blogging…

    IELTS Coaching in chennai

    German Classes in Chennai

    GRE Coaching Classes in Chennai

    TOEFL Coaching in Chennai

    spoken english classes in chennai | Communication training


    ReplyDelete
  61. 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
  62. 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

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

    ReplyDelete
  64. I think this is the minimum value to earn more than just commit
    artificial intelligence course in noida

    ReplyDelete
  65. 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
  66. Amazing 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.
    Simple Linear Regression
    Correlation vs covariance
    data science interview questions
    KNN Algorithm
    Logistic Regression explained

    ReplyDelete
  67. 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
  68. 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
  69. Superb exertion to make this blog more awesome and appealing.
    hrdf claimable

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

    ReplyDelete
  71. 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
  72. Very wonderful article. I liked reading your article. Very wonderful share. Thanks ! .
    Data Science Course In Bangalore With Placement

    ReplyDelete
  73. 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
  74. 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
  75. 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