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 :)
nike air jordan shoes
ReplyDeletenike outlet store online
coach store
jordan shoes
fitflops clearance
polo shirts
chanel handbags
hermes bag
nike shoes wholesale
coach outlet
coach factory
nike air max
pink jordans
lebron james shoes 2015
nike store
canada goose sale online
ugg boots
canada goose outlet
canada goose coats on sale
cheap wholesale jordans
michael kors factory outlet
cheap michael kors purses
gucci bags
christian louboutin shoes
christian louboutin
michael kors outlet
mbt shoes
cheap nike air max
salvatore ferragamo
fendi shoes
mont blanc legend
toms outlet factory
jordan 11
louboutin shoes
cheap canada goose jackets
north face sale
nike basketball shoes
polo shirts for men
discount nike
hermes outlet online
cheap michael kors
north face outlet store
coach sale
michael kors handbags
michael kors outlet
1010HXT
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
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.
ReplyDeleteSEO Company 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
cheap nhl jerseys
ReplyDeleteoakley sunglasses
rolex replica watches
michael kors handbags wholesale
versace
longchamps
coach factory outlet
yeezy boost 350
nhl jerseys
kobe 9 elite
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
ferragamo shoes
ReplyDeleteadidas outlet
moncler outlet
coach outlet
canada goose jackets
michael kors outlet store
uggs
cheap jordans
coach factory outlet
moncler jackets outlet
linpingping10.25
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
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.
ReplyDeleterpa training in chennai
rpa training in bangalore
rpa course in bangalore
best rpa training in bangalore
rpa online training
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.
ReplyDeletepython course in pune
python course in chennai
python course in Bangalore
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
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.
ReplyDeleteBest Devops training in sholinganallur
Devops training in velachery
Devops training in annanagar
Devops training in tambaram
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
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.
ReplyDeleteAWS 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
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شركة عزل اسطح بالجبيل
شركة مكافحة النمل الابيض بالاحساء
شركة عزل اسطح براس تنوره
شركة عزل اسطح بالاحساء
Я бы рекомендовал использовать профиль для светодиодных лент это нужно для того что бы лента дольше служила.
ReplyDeleteIt is very good and very informative. There is a useful information in it.Thanks for posting...
ReplyDeletehttps://www.apponix.com/
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
Great Post Thanks for sharing
ReplyDeleteSalesforce Training in Chennai
Microsoft Azure Training in Chennai
Openstack Training 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
cool stuff you have and you keep Python classes in pune overhaul every one of us
ReplyDeleteI 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
I really enjoyed while reading your article and it is good to know the latest updates. Do post more.
ReplyDeleteSalesforce Training in Chennai
salesforce developer training in chennai
salesforce certification in chennai
Angular 5 Training in Chennai
ccna course in Chennai
ReactJS Training in Chennai
Tally Training in Chennai
Salesforce Training in Porur
Salesforce Training in Tambaram
Salesforce Training in Adyar
valuable blog,Informative content...thanks for sharing, Waiting for the next update...
ReplyDeletecore java training in chennai
core java training
core java course
core java training in T nagar
core java training in Guindy
C C++ Training in Chennai
javascript training in chennai
Hibernate Training in Chennai
LoadRunner Training in Chennai
Mobile Testing Training in Chennai
Wonderful Blog.... Thanks for sharing with us...
ReplyDeleteHadoop Training in Chennai
Big data training in chennai
big data course
Hadoop Course in Chennai
Big data training in vadapalani
Hadoop training in porur
Python Training in Chennai
JAVA Training in Chennai
Selenium Training in Chennai
Software testing training in chennai
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.
ReplyDeleteExcelR Data Analytics Courses Online
Great info. The content you wrote is very interesting to read. This will be loved by all age groups.
ReplyDeleteDevOps Training in Chennai
Best DevOps Training in Chennai
DevOps Training institute in Chennai
Azure Training in Chennai
VMware Training in Chennai
RPA Training in Chennai
DevOps Training in Velachery
DevOps Training in Tambaram
DevOps Training in Adyar
DevOps Training in Vadapalani
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
For AI training in Bangalore, Visit:
ReplyDeleteArtificial Intelligence training in Bangalore
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
Rpa Training in Chennai
ReplyDeleteRpa Course in Chennai
Blue prism training in Chennai
Data Science Training In Chennai
Data Science Course In Chennai
Data Science Course In Chennai
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…!
ReplyDeletemagento training course in chennai
magento training institute in chennai
magento 2 training in chennai
magento development training
magento 2 course
magento developer training
This is the first & best article to make me satisfied by presenting good content. I feel so happy and delighted. Thank you so much for this article.
ReplyDeleteLearn Best Digital Marketing Course in Chennai
Digital Marketing Course Training with Placement in Chennai
Best Big Data Course Training with Placement in Chennai
Big Data Analytics and Hadoop Course Training in Chennai
Best Data Science Course Training with Placement in Chennai
Data Science Online Certification Course Training in Chennai
Learn Best Android Development Course Training Institute in Chennai
Android Application Development Programming Course Training in Chennai
Learn Best AngularJS 4 Course Online Training and Placement Institute in Chennai
Learn Digital Marketing Course Training in Chennai
Digital Marketing Training with Placement Institute in Chennai
Learn Seo Course Training Institute in Chennai
Learn Social Media Marketing Training with Placement Institute in Chennai
Thanks for sharing an informative blog keep rocking bring more details.I like the helpful info you provide in your articles. I’ll bookmark your weblog and check again here regularly. I am quite sure I will learn much new stuff right here! Good luck for the next!
ReplyDeleteWeb Designing Training Institute in Chennai | web design training class in chennai | web designing course in chennai with placement
Mobile Application Development Courses in chennai
Data Science Training in Chennai | Data Science courses in Chennai
Professional packers and movers in chennai | PDY Packers | Household Goods Shifting
Web Designing Training Institute in Chennai | Web Designing courses in Chennai
Google ads services | Google Ads Management agency
Web Designing Course in Chennai | Web Designing Training in Chennai