Golang CGo: Passing and receiving strings with C

In this post, we will see how to pass strings to a C function and receive strings returned from a C function. CGo provides convenient functions C.CString and C.GoString to convert Golang string into C char * and vice versa.


It should be noted that C.CString returns a dynamically allocated char array and should be freed to avoid memory leaks.

If go compiler throws an error like this:

error: ‘free’ undeclared (first use in this function)

It is because you are missing stdlib.h include which provides the free function.
Note: stdlib.h should be included in Go file.

Golang: io.Reader to String or byte array

Request.Body in http package is an instance of io.ReadCloser, which in turn is an instance of io.Reader. Processing body of the request as io.Reader has several advantages. it is memory efficient. But there are times when we want it as string rather than stream. This short snippet converts io.Reader stream into string:

python – split string delimited by runs of whitespace

In python, a string can be split using string.split() function. This function splits a string using a delimiter.

Example:
>>> “split this string”.split(‘ ‘)
[‘split’, ‘this’, ‘string’]

>>> “split,this,string”.split(‘,’)
[‘split’, ‘this’, ‘string’]

The first and second example are delimited by ‘ ‘ and ‘,’ respectively. If suppose we want to delimit using runs of whitespace, we can use

Example:
>>> ”   split   this text   “.split()
[‘split’, ‘this’, ‘text’]

Thus by using split function without any arguments, python splits on runs of whitespace.