How to write a file with go code?

Hello i want to write into a .go file a hello world in go.
im trying this way but dosn’t work

			_ = ioutil.WriteFile("main.go", 
			"package main" +
			"import 'fmt' " +
			"func main()" +
			"{"+
				"fmt.Println('hello world')" +
			"}"
			,
			0644)

What do you mean by “doesn’t work?” One thing I notice here is that you don’t seem to have any line breaks in the actual string. Maybe try the backticks instead, e.g.:

ioutil.WriteFile("main.go", `package main

import "format"

//...
`)
1 Like

I mean that it gives error, with your code it says

too few arguments in call to ioutil.WriteFilecompilerWrongArgCount

cannot use package main import "format" //... (untyped string constant “package main\n\t\t\t\timport “format”\n\t\t\t\t//…\n\t\t\t\t”) as []byte value in argument to ioutil.WriteFilecompilerIncompatibleAssign

I didn’t give a complete example. My point was that when you have "package main" + "import 'fmt'" + ..., you end up with a string of text all on one line. Instead of using separate strings and appending them together, just use backticks (`) around the string and then you don’t need to append the strings together.

1 Like

there was something mising an it was

		   dataString :=
				`
			package main
			import "fmt"

			func main(){
				fmt.Println("Hello World")
			}
			`
			dataBytes := []byte(dataString)
			ioutil.WriteFile("main.go", dataBytes, 0)

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.