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 :)
If I was really bored, I'd write a further iteration of this program that constructs itself :)
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.
ReplyDeleteWeb Designing Training in Chennai
Interesting Article
ReplyDeleteJavascript Training in Chennai | HTML5 Online Training
JavaScript Training Courses | Javascript Online Training | Angular 2 Training in Chennai
you had to share this style content is fantastic info for me.I'm read find that some content line very interesting.
ReplyDeleteHadoop Course in Chennai
Hadoop Training in Chennai
Informatica Training
Wonderful article...Its very useful for me..
ReplyDeleteSoftware Testing Training Institute in Chennai | Software Testing Training in Chennai | Best Software Testing Training in Chennai | No.1 Testing Training in Chennai
Nice Blog..Thanks for sharing..
ReplyDeleteEmbedded System Training in Chennai | Embedded System Course in Chennai | No.1 Embedded Training Institute in Chennai | Online Embedded Training in Chennai
Thanks for sharing beautiful blog to read.I read so many blogs.your blog is amazing..
ReplyDeleteSoftware Testing Training Center in Chennai |Best Selenium Training Institute in Chennai | RPA Training Institute in Chennai
ReplyDeleteexcellent 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
I have been meaning to write something like this on my website and you have given me an idea. Cheers.
ReplyDeleteJava training in Bangalore | Java training in Marathahalli
Java training in Bangalore | Java training in Btm layout
Java training in Bangalore |Java training in Rajaji nagar
Java training in Bangalore | Java training in Kalyan nagar
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.
ReplyDeleteData Science Training in Chennai | Best Data science Training in Chennai
Data Science training in kalyan nagar
Data science training in Bangalore | Data Science training institute in Bangalore
Data Science training in marathahalli | Data Science training in Bangalore
Data Science interview questions and answers
Data science training in jaya nagar | Data science Training in Bangalore
This comment has been removed by the author.
ReplyDeleteI 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
ReplyDeleteSome us know all relating to the compelling medium you present powerful steps on this blog and therefore strongly encourage
ReplyDeletecontribution 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شركة عزل اسطح بالجبيل
شركة مكافحة النمل الابيض بالاحساء
شركة عزل اسطح براس تنوره
شركة عزل اسطح بالاحساء
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.
ReplyDeleteAWS Training Institute in Chennai | AWS Certification Training in Velachery | AWS Exam Center in Chennai | AWS Online Exams in Chennai
Your blog is very useful for me,thanks for sharing such a wonderful post with useful information.keep updating..
ReplyDeletePython Training Center in Chennai | Python Certification Training in Chennai
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.
ReplyDeleteHome Mart is a site about Home Improvement, Furniture, Home Appliances and many more.
ReplyDeleteCheck out the best
entertainment unit
shoe rack
I really impressed to visit your great blog. Thank you for sharing with us...
ReplyDeleteEmbedded System Course Chennai
Embedded Training in Chennai
Placement Training in Chennai
Soft Skills Training in Chennai
JMeter Training in Chennai
Appium Training in Chennai
Pega Training in Chennai
Power BI Training in Chennai
Tableau Training in Chennai
Oracle Training in Chennai
Advanced Excel Training in Chennai
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!!
ReplyDeleteArtificial Intelligence Course
ReplyDeleteNice information, want to know about Selenium Training In Chennai
Selenium Training In Chennai
Data Science Training In Chennai
Protractor Training in Chennai
jmeter training in chennai
Rpa Training Chennai
Rpa Course Chennai
Selenium Training institute In Chennai
Python Training In Chennai
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.
ReplyDeleteAwesome 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!
ReplyDeleteData Science Institute in Bangalore
Very informative post ! There is a lot of information here that can help any business get started with a successful social networking campaign !
ReplyDeleteData Science Certification in Bangalore
I see the greatest contents on your blog and I extremely love reading them.
ReplyDeleteI 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!
ReplyDeleteArtificial Intelligence Training in Chennai
Ai Training in Chennai
Artificial Intelligence training in Bangalore
Ai Training in Bangalore
Artificial Intelligence Training in Hyderabad | Certification | ai training in hyderabad
Artificial Intelligence Online Training
Ai Online Training
Blue Prism Training in Chennai
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
ReplyDeleteJava 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
ou 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.
ReplyDeleteangular js training in chennai
angular training in chennai
angular js online training in chennai
angular js training in bangalore
angular js training in hyderabad
angular js training in coimbatore
angular js training
angular js online training
Really nice and interesting post. I was looking for this kind of information and enjoyed reading this one. Keep posting. Thanks for sharing.
ReplyDeletemachine learning course training in guduvanchery
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
ReplyDeleteI 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.
ReplyDeleteit course
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...
ReplyDeleteAWS Course in Bangalore
AWS Course in Hyderabad
AWS Course in Coimbatore
AWS Course
AWS Certification Course
AWS Certification Training
AWS Online Training
AWS Training
This post is very easy to read and appreciate without leaving any details. Great work! Great work!
ReplyDeletedata science course in delhi
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.
ReplyDeleteacte 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
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.
ReplyDeletewhat is hrdf
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.
ReplyDeleteData 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
ReplyDeleteThere is plainly a ton to consider this. Keep working, remarkable work!
https://360digitmg.com/course/project-management-professional-pmp
jordan shoes
ReplyDeletegoyard handbags
golden goose outlet
yeezy supply
yeezy shoes
yeezy
goyard handbags
golden goose
yeezy
yeezy shoes
I think this is the minimum value to earn more than just commit
ReplyDeleteartificial intelligence course in noida
I was looking at a portion of your posts on this site and I consider this site is really enlightening! Keep setting up..
ReplyDelete360DigiTMG big data course malaysia
Superb exertion to make this blog more awesome and appealing.
ReplyDeletehrdf claimable
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.
ReplyDeleteartificial intelligence course in bangalore
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.
ReplyDeletedata science training in hyderabad
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.
ReplyDeletedifference between analysis and analytics
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
ReplyDeleteIn fact it may be easier and simpler to teach a computer to learn, then add an actual organic brain. data science course in india
ReplyDeleteThis is good information and really helpful for the people who need information about this.
ReplyDeletejava substring
string manipulation programs in java
string handling functions in java
date format in java
advantages of aws
software testing interview question and answer
php interview questions and answers for experienced
Amazing blog.Thanks for sharing such excellent information with us. keep sharing...
ReplyDeletedigital marketing training in aurangabad
Mua vé máy bay tại Aivivu, tham khảo
ReplyDeletevé máy bay đi Mỹ bao nhiêu tiền
vé máy bay tphcm ra hà nội
vé máy bay hà nội sài gòn tháng 10
vé khứ hồi hà nội nha trang
giá vé máy bay từ mỹ về việt nam
taxi đi sân bay
combo khách sạn quy nhơn
Thanks for sharing nice information....
ReplyDeletebest data science course in pune
Wow, amazing post! Really engaging, thank you.
ReplyDeletebest machine learning course in aurangabad
Thank you for taking the time to publish this information very useful!
ReplyDeletePython Training in Hyderabad
Python Course in Hyderabad
I am impressed by the information that you have on this blog. It shows how well you understand this subject.
ReplyDeleteData Science Training in Hyderabad
Data Science Course in Hyderabad
Greetings! Very helpful advicde in this particular post! It’s the little changes that make the greatest changes online cbd store
ReplyDeleteNice this information is very useful. it is valuable and informative for me. Thanks for sharing these information with all of us. whatsapp mod
ReplyDeleteA 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.
ReplyDeletedata analytics course in hyderabad
We are really grateful for your blog post. You will find a lot of approaches after visiting your post. Great work
ReplyDeletefull stack web development course in malaysia
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.
ReplyDeletewhat does health insurance cover
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
ReplyDeleteGreat 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
ReplyDeleteI 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
ReplyDelete360DigiTMG offers the best Data Science certification course in the market with placement assistance. Get trained by IIT, IIM, and ISB alumni.
ReplyDeleteBusiness Analytics Course in Jodhpur
Thanks for the blog very nice keep going.smtp server for bulk mailing
ReplyDeletebulk email service provider
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.
ReplyDeleteFor more info visit High DA PA Article Submission Sites