pointers,interface,go , Why can't the interface be implemented with pointer receivers


Why can't the interface be implemented with pointer receivers

Question:

Tag: pointers,interface,go

I'm confused as to why this fails to compile with:

impossible type assertion: Faz does not implement Foo (Bar method has pointer receiver)

if I make the receiver for Faz.Bar a Faz value rather than a Faz pointer then it compiles fine, but I thought it was always better to have pointer receivers so values aren't being copied around?

package main

import (
    "log"
)

func main() {
    foo := New().(Faz)
    log.Println(foo)
}

type Foo interface {
    Bar() string
}

func New() Foo {
    return &Faz{}
}

type Faz struct {
}

func (f *Faz) Bar() string {
    return `Bar`
}

Answer:

Because it's *Faz not Faz.

func main() {
    foo := New().(*Faz)
    log.Println(foo)
}

Related:


How to pass pointer to struct to a function?


c,function,pointers,struct
I am instantiating the struct within the main() function and I am passing a pointer to this structure over to a function. I would like to then pass this pointer to the original struct to another function, how would I do this? I am now lost in pointerception. struct coords...

Interface for Child Class that Inherits from parent class without reimplementing parent class


c#,oop,inheritance,interface
Currently I have the following: public class ChildClass : ParentClass {... ParentClass implements an interface as follows (I need ParentClass to be instantiated and therefore can't be abstract): public class ParentClass : IParentClass {... I also want child class to implement an interface so that I can mock this class...

function pointer is not a function or function pointer


c++,function,pointers
I have following problem: void MyClass::LoopFunction(vector<Item>& items,void (MyClass::*funcy)(vector<Item>&,int)) { for(SInt32 i = 0; i < 50; i++) { funcy(items,i); } } It says: Called object type 'void(MyClass::*)(vector<Item>&,int)' is not a function or function pointer Can anyone help me to find a solution for this?...

Controller with same structure not working using an interface


c#,asp.net-mvc,interface,datacontext
I have created 8 models and controllers respectively for my Project using the same structure, however now this structure is not working. It is giving me this error: The current type, HelpDesk.Contracts.Repositories.IRepositoryBase`1[HelpDesk.Model.Knowledgebase], is an interface and cannot be constructed. Are you missing a type mapping? Here is my interface: namespace...

create ndarray out of c++ pointer


python,c++,pointers,numpy,cython
I created a module in c++ and need to use the results in python. Already wrote a wrapper and it is working with this code a = np.empty([r, hn]) for i in xrange(r): for j in xrange(hn): a[i,j]=self.thisptr.H[i*hn+j] return a The code is working, but I think there should be...

Difference between the use of pointers for array and single data point?


c++,arrays,pointers
#include <iostream> using namespace std; const int MAX = 3; int main () { int var[MAX] = {10, 100, 200}; int *ptr; // let us have array address in pointer. ptr = var; for (int i = 0; i < MAX; i++) { cout << "Address of var[" << i...

passing arguments via reference and pointer C++


c++,function,pointers,reference
I am looking at a code snippet and I have this sequence. class MyVariable { .... CustomType z; .... } A.cpp calling a function f ( & myVariable) In an included file I do have this : B.h void f ( MyVariable * myVariable); B.cpp f( MyVariable * myVariable){ CustomType...

Are interfaces a valid substitute for utility classes in Java 8? [duplicate]


java,class,interface,java-8,utility-method
This question already has an answer here: Java 8: Interface with static methods instead of static util class 4 answers For the past decade or so, I've been using the pattern below for my Java utility classes. The class contains only static methods and fields, is declared final so...

Cannot convert type via a reference conversion, boxing conversion, unboxing conversion, wrapping conversion, or null type conversion


c#,interface,type-conversion
In C#, if I have a parameter for a function where the parameter type is of an interface, how do a pass in an object that implements the interface. Here is an example: The parameter for a function is as follows: List<ICustomRequired> The list that I already have is as...

How exactly do pointers in Fortran differ from C/C++ pointers?


c++,c,pointers,fortran
It might be useful to have both C/C++ programmers and Fortran programmers compare and contrast pointers in these two languages. In trying to explain to C/C++ programmers how Fortran pointers differ, I usually say pointers to functions or subroutines do not exist. I then try to make the argument that...

Generic Interface missing implementation


vb.net,interface,implements,generic-interface
I have a generic interface, even if I state the type when I implement it, it says the implemented classes misses all implementation of members. The interface Interface IBuilder(Of T) Function Number(ByVal literal As String) As T End Interface The implement Class BracketsBuilder Implements IBuilder(Of String) Public Function Number(number__1 As...

Passing iterator's element to a function: wrong type of pointer


c++,pointers,stl,iterator
I'm attempting to solve Project Euler's problem #3 using C++ to gain an understanding of how to use C++ iterators. According to the examples I've seen online, I can use the dereferened iterator as a parameter for cout, and it will print the elements successfully. By that same logic, I...

In C language, What is the difference between extern buffer[] and extern *buffer?


c,arrays,pointers
I read the below piece of information in a microsoft article; https://support.microsoft.com/en-us/kb/44463 The text below presents an example of a common programming mistake, that is, confusing an array and a pointer declaration: Consider an application divided into several modules. In one module, declare an array as follows: signed char buffer[100];...

Pointer Referring to an Array


c++,arrays,pointers
Recently, I've been trying to strengthen my skills with pointers, and I ran into the following issue: I have the following piece of code, but I run into a runtime error. I tried looking up some stuff about iterating through a pointer that represents an array, but I couldn't find...

Under Xcode 6.3, NULL C++ reference address evaluates as non-zero


c++,xcode,pointers,memory-alignment,type-safety
Similar to this question: XCode 6.3 Warning : Comparison of address of 'myObject' not equal to null pointer is always true with C++, I found that previously working code for evaluating null pointers stopped working: struct AStruct { int x, y; char *name; }; AStruct& GetStruct() { return *(AStruct*)0; }...

Program to reverse a string in C without declaring a char[]


c,string,pointers,char
I need to reverse a given string and display it without using the value At[index] notation , I tried the below program using pointers,but it does not print anything for the reverse string, Please help! int main() { char* name=malloc(256); printf("\nEnter string\n"); scanf("%s",name); printf("\nYou entered%s",name); int i,count; count=0; //find the...

Get List of Elements in Tree with specific Field Value


vb.net,linq,properties,interface
I have an Interface like this: Public Interface TreeSelectorAttributes Property selectedInTreeSelector As Boolean Property Name As String ReadOnly Property childs As IEnumerable(Of TreeSelectorAttributes) End Interface and I have a TreeView which has a List of this TreeSelectorAttributes: Public Property rootList As IEnumerable(Of TreeSelectorAttributes) now after the User chooses which elements...

memory content not erased after deleting my pointer (on a simple example) [duplicate]


c++,pointers,memory-management
This question already has an answer here: Can a local variable's memory be accessed outside its scope? 16 answers Here is a simple of example of a question I have: I create a pointer of integer (value 5), I print the pointer (hence the address) of the memory case...

Access violation on try to fill dynamic array (large number of items)


c,arrays,pointers,malloc,dynamic-memory-allocation
I have the following C code: int dimension; double *AtS; ... AtS=(double*)malloc(sizeof(double)*dimension); for (i=0; i<dimension; i++) { AtS[i]=0.0; } While dimension is ~6-8 millions it works fine, but when it about 300 millions it fails with access violation. The following message in debug: Unhandled exception at 0x012f1077 in mathpro.exe: 0xC0000005:...

C# How i use linq with explicit interface attribute?


c#,linq,inheritance,interface,explicit
i have one class with two inheritance interfaces and yours attributes are explicits because both have some equals attributes, so, i need use LINQ with this class, but i can't access the explicits attributes when i use "select new Foo" ... look the case: public class QuestaoMontaProva : IQuestao, IExercicio...

Although maps are always reference types, what if they're returned from a non-pointer receiver?


pointers,dictionary,go
Supposedly maps are reference types in Go, so when returning them from functions, you don't need to pass as a pointer to the map in order for the changes to be visible outside the function body. But what if said map is returned from a method on a non-pointer struct?...

Print addresses of all local variables in C


debugging,pointers,gcc,gdb,memory-address
I want to print the addresses of all the local and global variables which are being used in a function, at different points of execution of a program and store them in a file. I am trying to use gdb for this same. The "info local" command prints the values...

Fighter class does not implement interface member


c#,class,interface
And I am getting this error: Error 1 'Fight.Fighter' does not implement interface member 'Fight.IFighter.Utok(Fight.IFighter)' This is the first time I am trying to learn working with interfaces, so sorry for dump question. Any ideas? I have following code: Interface: interface IFighter { string GraphicLife(); bool IsLive(); int Obrana(int utocneCislo);...

Java: Abstract classes methods and interface


java,interface,abstract
The program below calculates the total of the areas of any number of shapes instantiated. The problem is that I don't know how to output the draw() method of the interface. Here is the main class: public class MyClass1{ public static void main(String[] args) { Shape[] shapes= new Shape[3]; shapes[0]=...

Function pointer to singleton class instance function


c++,oop,pointers,singleton
What I'm trying to do is create a function pointer to a single class instance function. I want to do this so I can do something like this: C->member_method(); instead of: Config::inst()->member_method(); but I'm not sure how to go about it. Here is my singleton class: class Config { private:...

“Attempting to use an incompatible return type” with Interface Inheritance


java,inheritance,interface
I'm running into a problem with incompatible return types using inheritance. public interface A { } public interface B extends A { } public interface C { Map<String, A> getMapping(); } public interface D extends C { Map<String, B> getMapping(); } Is there a way to make this work? Right...

Why I cannot use “fgets” to read a string to an element of my Struct?


c,pointers,memory-management,struct,fgets
I'm trying to create a program almost like "bank" using struct, but when the program should have read the string (variable "nome" that is name in portuguese) it totally ignore the "fgets" that I used. This is the part that I was talking about : printf("\nNome: \n"); fgets(vet[cont+1].nome, sizeof(vet[cont+1].nome), stdin);...

converted string failed to contain correct values of float


c,pointers,char
I am facing problem in converting float to char*. I have written a function that will put integer part of float in string and then decimal values. I need it for two places of decimal. But something is horribly wrong. Either it ouputs integer value or just 1 place after...

double* android ndk crash


c++,pointers,android-ndk
I'm facing a peculiar problem with the android ndk. I'm trying to read a previously stored set of bytes in an unsigned char* readBytes (previous allocated and read from file). The data needs to be interpreted as double. unsigned char* svDataOffset=(unsigned char*)(readBytes+byteCounter); unsigned char* chars=(unsigned char*)(svDataOffset+2); //offset of 2 is...

Utility method expects interface and doesn't accept a class that implements said interface [duplicate]


java,interface
This question already has an answer here: Why we can't do List<Parent> mylist = ArrayList<child>(); 2 answers I'm working on a web development project, and I'm working on several apps with "news feed" functionality. I want to make sure that every item with a picture flips a switch back...

Why can't I use `&&a` in C?


c,pointers,operators,address-operator
int main(int argc, char * argv[]) { int a = 10; int * sp = &a; int * * dp1 = &sp; int * * dp2 = &&a; // NG int * * dp3 = &(&a); // NG int * * dp4 = &((int *) &a); // NG } $...

Call template function for the value of a pointer out of a template function, in C++


c++,templates,pointers,c++11
I am trying to call a template function for the pointer that was given as template parameter in my calling function. My code is: template <> struct serialize_helper<std::string> { // not important code... } }; template <class T> inline void serializer(const T& obj, StreamType::iterator& res) { if(std::is_pointer<T>::value) { //THIS doesn'...

Interface constant declaration example in Java's SDK


java,interface,constants
Is there an example of an Interface in Java's built-in library (JDK) that contains a constant field? From the documentation, constant declaration can be defined in interfaces, but I can't remember seeing such. public interface OperateCar { // constant declarations, if any ... } ...

Is there a way to restrict a pointer from being modified by specific functions?


c,pointers
This builds off of my previous question: Is this an appropriate use of const qualifiers in C? In Vector.h: typedef struct _Vector Vector; Vector* vector_init(const UInt32 size); void* vector_get(const Vector *v, UInt32 idx); void vector_add(Vector *v, void* const elem); void vector_set(Vector *v, const UInt32 idx, void* const elem); ...etc In...

Can assignment from a const_iterator dereference cause undefined behaviour?


c++,pointers,pass-by-reference,undefined-behavior,const-iterator
This code is a simplified test for something I am trying to do for real elsewhere. I have a function which takes a "ref-to-ptr" argument and modifies it to return a pointer from a list of pointers. #include <iostream> #include <list> using namespace std; typedef int* intp; typedef std::list<intp> intplist;...

pointer to pointer dynamic array in C++


c++,arrays,pointers
I've been having bad luck with dynamic pointers when I want to close it. why the application wrote to memory after end of heap buffer? how can I close my array? int main() { . . int **W; W = new int* [n]; for (int i=1; i <= n; i++)...

Methods defined in an interface can no be used from another class


c#,entity-framework,interface
I am using Entity Framework 4.1 and code-first approach. I have the following intefaces namespace BackupCore.Contracts { public interface IEntity { DbSet getDbSet(BackupCoreContainer context); bool isNew() ; } } namespace BackupCore { interface IDao<IEntity> { IEntity Save(IEntity ent); IQueryable<IEntity> GetAll(); bool Delete(IEntity ent, out String errMsg); void SaveChanges(); } }...

Pointer parameter was set but never used warning


c,pointers,compiler-warnings,suppress-warnings,keil
I have the following function: void foo(char *ptr_1) { char *ptr_2; bar(ptr_2); ptr_1 = ptr_2; } And get this warning: parameter "ptr_1" was set but never used I understand that the warning is technically true, but is irrelevant at the same time. I could suppress it with: (void)(ptr_1) But is...

Parameters to use in a referenced function c++


c++,pointers,reference
I am very confused as to what kind of variables I would put into my function here: names. I am doing a practice problem in a C++ book, because I am learning C++ and am on References and pointers right now, and cannot find a solution. Just for background information,...

binary tree code does not work properly


c,pointers
I made a tree structure, read words from file and registered them to the tree. But the enter() does not work properly. I debuged with gdb and set a break point line 42. Then I entered print *node print *root. (gdb) print node $9 = (struct node *) 0x603250 (gdb)...

Functions with pointer arguments in C++


c++,function,pointers,constructor,ampersand
I'm having some difficulties in understanding some aspects of functions with pointers. Here is the code I'm running: #include <iostream> using namespace std; class Item { public: Item(Item * it) { data = it->data; } Item(int d) { data = d; } void printData() { cout << data << endl;...

Laravel Interfaces


php,laravel,interface,namespaces
I used the following tutorial to get an idea about interfaces: http://vegibit.com/what-is-a-laravel-interface/ But I wanted to change the directory of where I am putting my interfaces to "App/Models/Interfaces". And so I did. But now I cannot get it to work anymore. Here is my code: Routes.php App::bind('CarInterface', 'Subaru'); Route::get('subaru', function()...

What are the advantages of explicit interface implementation in C#? [duplicate]


c#,inheritance,interface,implementation
This question already has an answer here: C# Interfaces. Implicit implementation versus Explicit implementation 11 answers C# supports built-in mechanism for differentiating methods that have the same names. Here is a simple example below shows how it works: interface IVehicle{ //identify vehicle by model, make, year void IdentifySelf(); }...

Allocate a new bool array pointer


c++,arrays,pointers
I'm curious how you go about allocating a new boolean array pointer in c++. I did some looking around but couldn't find anything that is similar to how I've learned to allocate new pointers. To allocate a new int pointer I have learned to do int * intPointer = new...

Using [] on pointers in C?


c,pointers,indexing
Right now I'm looking over some C code and they have some pointer syntax that I'm confused about. So first they declared a pointer like so: int32_t *p_tx_buf=NULL; Then later on they wrote: p_tx_buf = malloc(...math... ); The stuff in the middle is just math to calculate the size of...

Passing Pointers through a Function Then Getting Giberish


c++,function,pointers
I've got the following code, and it seems to be printing gibberish. However, when I change the size of the array from "r" to 5000, it works perfectly. Can anyone explain this behavior and show me how to fix it? I've done a lot of research on this, but can't...

Why is interface variable instantiation possible?


c#,variables,interface,instance
As far as I know, interfaces cannot be instantiated. If this is true, why does the below code compile and execute? It allows you to create a variable interface. Why is this possible? Interface: public interface IDynamicCode<out TCodeOut> { object DynamicClassInstance { get; set; } TCodeOut Execute(string value = "");...

Golang switch between structs


struct,go,interface,switch-statement
I'm new to golang and I'm trying to create a function that, based on the struct it's used on, will return a formatted string using Sprintf type Name struct { Title string First string Last string } type Location struct { Street string City string State string Zip string }...

Does realloc() invalidate all pointers?


c,pointers,dynamic-memory-allocation,behavior,realloc
Note, this question is not asking if realloc() invalidates pointers within the original block, but if it invalidates all the other pointers. I'm new to C, and am a bit confused about the nature of realloc(), specifically if it moves any other memory. For example: void* ptr1 = malloc(2); void*...

modifying double pointer to an integer array


c,arrays,pointers,double-pointer
void function(int **arr); int main() { int *array; array=calloc(4, sizeof(int)); function(&array); return0; } void function(int **arr) { int *tmp; tmp=calloc(4, sizeof(int)); tmp[0]=1; tmp[1]=2; tmp[2]=3; tmp[3]=4; } I want to assign tmp to arr. how can I do it?...