There are currently no frequently asked questions associated with this exercise – that’s where you come in! You can contribute to this section by offering your own questions, answers, or clarifications on this exercise. Ask or answer a question by clicking reply () below.
If you’ve had an “aha” moment about the concepts, formatting, syntax, or anything else with this exercise, consider sharing those insights! Teaching others and answering their questions is one of the best ways to learn and stay sharp.
Join the Discussion. Help a fellow learner on their journey.
Ask or answer a question about this exercise by clicking reply () below!
You can also find further discussion and get answers to your questions over in Language Help.
Agree with a comment or answer? Like () to up-vote the contribution!
func squareInfo(side float64) string {
var area float64 = side * side
var perimeter float64 = side * 4
var message string = fmt.Printf("The area of this square is %d and the perimeter is %d", area, perimeter)
return message
gives an error of “# command-line-arguments
./main.go:14:7: assignment mismatch: 1 variable but fmt.Printf returns 2 values”
How do I go about fixing this. I understand it returns the bytes written and any write error message (n int, err error). But what can be done?
Printf formats according to a format specifier and writes to standard output. It returns the number of bytes written and any write error encountered.
Based on your code, the purpose of your squareInfo function is to carry out some calculations and return a properly formatted string.
In your current code, you are trying to print a string and then attempting to assign the return values of Printf to a string variable message. This is causing problems.
Instead of printing and making use of the bytes or error, your goal is to create a properly formatted string, assign it to the variable message and then return this string.
The appropriate function for this task is fmt.Sprintf:
Sprintf formats according to a format specifier and returns the resulting string.
Also, %d is used for integers, whereas you have declared area and perimeter as floats. Therefore you should use %f. Or better still use %.2f or some other precision of your choice to format how many digits after the decimal are shown.
func squareInfo(side float64) string {
var area float64 = side * side
var perimeter float64 = side * 4
var message string = fmt.Sprintf("The area of this square is %.2f and the perimeter is %.2f", area, perimeter)
return message
}
In main, you can then either print the result of a function call directly, OR you can assign the result to a variable and then print it:
func main() {
// Print the result of function call directly
fmt.Println(squareInfo(11.5))
// OR
// Save result to a string and then print it
var result string = squareInfo(11.5)
fmt.Println(result)
}
// Output:
// "The area of this square is 132.25 and the perimeter is 46.00"